感谢支持
我们一直在努力

实现Linux下上下键和命令补全

可以用readline库
安装readline
在eclipse中编译使用readline需要在连接时加上-Ireadline      -Itermcap

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>


static char *line_read = (char *) NULL;


char *rl_gets() {
 if (line_read) {
  free(line_read);
  line_read = (char *) NULL;
 }
 line_read = readline(“Please Enter:”);


 if (line_read && *line_read)
  add_history(line_read);
 return (line_read);
}


int main() {
 char *mline;
 mline = rl_gets();
 printf(“%s\n”, mline);
}


教学资料

http://www.linuxidc.com/Linux/2011-04/34579p3.htm


用libedit库

用这库需要安装libedit和ncurses-5.6  readline是GPL的,这两个是非GPL的


一个linux命令示列


  1. /* fileman.c — A tiny application which demonstrates how to use the  

  2.  GNU Readline library.  This application interactively allows users  

  3.  to manipulate files and their modes.  

  4.  

  5.  NOTE: this was taken from the GNU Readline documentation and ported  

  6.  to libedit. A commad to output the history list was added.  

  7.  

  8.  */ 

  9.  

  10. #include <stdio.h>  

  11. #include <sys/types.h>  

  12. #include <sys/file.h>  

  13. #include <sys/stat.h>  

  14. #include <sys/errno.h>  

  15. #include <ctype.h>  

  16. #include <string.h>  

  17. #include <stdlib.h>  

  18. #include <unistd.h>  

  19. #include <locale.h>  

  20. #include <time.h>   

  21.   

  22. /* GNU readline  

  23.  #include <readline/readline.h>  

  24.  #include <readline/history.h>  

  25.  */ 

  26. #include <editline/readline.h>   

  27.   

  28. void * xmalloc(size_t size);   

  29. void too_dangerous(char *caller);   

  30. void initialize_readline();   

  31. int execute_line(char *line);   

  32. int valid_argument(char *caller, char *arg);   

  33.   

  34. typedef int rl_icpfunc_t(char *);   

  35.   

  36. /* The names of functions that actually do the manipulation. */  

  37. int com_list(char *);   

  38. int com_view(char *);   

  39. int com_history(char *);   

  40. int com_rename(char *);   

  41. int com_stat(char *);   

  42. int com_pwd(char *);   

  43. int com_delete(char *);   

  44. int com_help(char *);   

  45. int com_cd(char *);   

  46. int com_quit(char *);   

  47.   

  48. /* A structure which contains information on the commands this program  

  49.  can understand. */  

  50.   

  51. typedef struct {   

  52.     char *name; /* User printable name of the function. */  

  53.     rl_icpfunc_t *func; /* Function to call to do the job. */  

  54.     char *doc; /* Documentation for this function.  */  

  55. } COMMAND;   

  56.   

  57. COMMAND commands[] = { { “cd”, com_cd, “Change to directory DIR” }, { “delete”,   

  58.         com_delete, “Delete FILE” }, { “help”, com_help, “Display this text” },   

  59.         { “?”, com_help, “Synonym for `help'” }, { “list”, com_list,   

  60.                 “List files in DIR” },   

  61.         { “ls”, com_list, “Synonym for `list'” }, { “pwd”, com_pwd,   

  62.                 “Print the current working directory” }, { “quit”, com_quit,   

  63.                 “Quit using Fileman” }, { “rename”, com_rename,   

  64.                 “Rename FILE to NEWNAME” }, { “stat”, com_stat,   

  65.                 “Print out statistics on FILE” }, { “view”, com_view,   

  66.                 “View the contents of FILE” }, { “history”, com_history,   

  67.                 “List editline history” }, { (char *) NULL,   

  68.                 (rl_icpfunc_t *) NULL, (char *) NULL } };   

  69.   

  70. /* Forward declarations. */  

  71. char *stripwhite(char *string);   

  72. COMMAND *find_command(char *name);   

  73.   

  74. /* The name of this program, as taken from argv[0]. */  

  75. char *progname;   

  76.   

  77. /* When non-zero, this means the user is done using this program. */  

  78. int done;   

  79.   

  80. char *   

  81. dupstr(char* s) {   

  82.     char *r;   

  83.   

  84.     r = (char*)xmalloc(strlen(s) + 1);   

  85.     strcpy(r, s);   

  86.     return (r);   

  87. }   

  88.   

  89. int main(int argc, char **argv) {   

  90.     char *line, *s;   

  91.   

  92.     progname = argv[0];   

  93.   

  94.     setlocale(LC_CTYPE, “”);   

  95.   

  96.     initialize_readline(); /* Bind our completer. */  

  97.   

  98.     stifle_history(7);   

  99.   

  100.     /* Loop reading and executing lines until the user quits. */  

  101.     for (; done == 0;) {   

  102.         line = readline(“FileMan: “);   

  103.   

  104.         if (!line)   

  105.             break;   

  106.   

  107.         /* Remove leading and trailing whitespace from the line.  

  108.          Then, if there is anything left, add it to the history list  

  109.          and execute it. */  

  110.         s = stripwhite(line);   

  111.   

  112.         if (*s) {   

  113.   

  114.             char* expansion;   

  115.             int result;   

  116.   

  117.             result = history_expand(s, &expansion);   

  118.   

  119.             if (result < 0 || result == 2) {   

  120.                 fprintf(stderr, “%s\n”, expansion);   

  121.             } else {   

  122.                 add_history(expansion);   

  123.                 execute_line(expansion);   

  124.             }   

  125.             free(expansion);   

  126.         }   

  127.   

  128.         free(line);   

  129.     }   

  130.     exit(0);   

  131.   

  132.     return 0;   

  133. }   

  134.   

  135. /* Execute a command line. */  

  136. int execute_line(char *line) {   

  137.     register int i;   

  138.     COMMAND *command;   

  139.     char *word;   

  140.   

  141.     /* Isolate the command word. */  

  142.     i = 0;   

  143.     while (line[i] && isspace(line[i]))   

  144.         i++;   

  145.     word = line + i;   

  146.   

  147.     while (line[i] && !isspace(line[i]))   

  148.         i++;   

  149.   

  150.     if (line[i])   

  151.         line[i++] = ‘\0’;   

  152.   

  153.     command = find_command(word);   

  154.   

  155.     if (!command) {   

  156.         fprintf(stderr, “%s: No such command for FileMan.\n”, word);   

  157.         return (-1);   

  158.     }   

  159.   

  160.     /* Get argument to command, if any. */  

  161.     while (isspace(line[i]))   

  162.         i++;   

  163.   

  164.     word = line + i;   

  165.   

  166.     /* Call the function. */  

  167.     return ((*(command->func))(word));   

  168. }   

  169.   

  170. /* Look up NAME as the name of a command, and return a pointer to that  

  171.  command.  Return a NULL pointer if NAME isn’t a command name. */  

  172. COMMAND *   

  173. find_command(char *name) {   

  174.     register int i;   

  175.   

  176.     for (i = 0; commands[i].name; i++)   

  177.         if (strcmp(name, commands[i].name) == 0)   

  178.             return (&commands[i]);   

  179.   

  180.     return ((COMMAND *) NULL);   

  181. }   

  182.   

  183. /* Strip whitespace from the start and end of STRING.  Return a pointer  

  184.  into STRING. */  

  185. char *   

  186. stripwhite(char *string) {   

  187.     register char *s, *t;   

  188.   

  189.     for (s = string; isspace(*s); s++)   

  190.         ;   

  191.   

  192.     if (*s == 0)   

  193.         return (s);   

  194.   

  195.     t = s + strlen(s) – 1;   

  196.     while (t > s && isspace(*t))   

  197.         t–;   

  198.     *++t = ‘\0’;   

  199.   

  200.     return s;   

  201. }   

  202.   

  203. /* **************************************************************** */  

  204. /*                                                                  */  

  205. /*                  Interface to Readline Completion                */  

  206. /*                                                                  */  

  207. /* **************************************************************** */  

  208.   

  209. char *command_generator(const char *, int);   

  210. char **fileman_completion(const char *, intint);   

  211.   

  212. /* Tell the GNU Readline library how to complete.  We want to try to  

  213.  complete on command names if this is the first word in the line, or  

  214.  on filenames if not. */  

  215. void initialize_readline() {   

  216.     /* Allow conditional parsing of the ~/.inputrc file. */  

  217.     rl_readline_name = “FileMan”;   

  218.   

  219.     /* Tell the completer that we want a crack first. */  

  220.     rl_attempted_completion_function = fileman_completion;   

  221. }   

  222.   

  223. /* Attempt to complete on the contents of TEXT.  START and END  

  224.  bound the region of rl_line_buffer that contains the word to  

  225.  complete.  TEXT is the word to complete.  We can use the entire  

  226.  contents of rl_line_buffer in case we want to do some simple  

  227.  parsing.  Returnthe array of matches, or NULL if there aren’t any. */  

  228. char **   

  229. fileman_completion(const char* text, int start, int end) {   

  230.     char **matches;   

  231.   

  232.     matches = (char **) NULL;   

  233.   

  234.     /* If this word is at the start of the line, then it is a command  

  235.      to complete.  Otherwise it is the name of a file in the current  

  236.      directory. */  

  237.     if (start == 0)   

  238.         /* TODO */  

  239.         matches = completion_matches(text, command_generator);   

  240.     /* matches = rl_completion_matches (text, command_generator); */  

  241.   

  242.     return (matches);   

  243. }   

  244.   

  245. /* Generator function for command completion.  STATE lets us  

  246.  know whether to start from scratch; without any state  

  247.  (i.e. STATE == 0), then we start at the top of the list. */  

  248. char *   

  249. command_generator(const char *text, int state) {   

  250.     static int list_index, len;   

  251.     char *name;   

  252.   

  253.     /* If this is a new word to complete, initialize now.  This  

  254.      includes saving the length of TEXT for efficiency, and  

  255.      initializing the index variable to 0. */  

  256.     if (!state) {   

  257.         list_index = 0;   

  258.         len = strlen(text);   

  259.     }   

  260.   

  261.     /* Return the next name which partially matches from the  

  262.      command list. */  

  263.     while (name = commands[list_index].name) {   

  264.         list_index++;   

  265.   

  266.         if (strncmp(name, text, len) == 0)   

  267.             return (dupstr(name));   

  268.     }   

  269.   

  270.     /* If no names matched, then return NULL. */  

  271.     return ((char *) NULL);   

  272. }   

  273.   

  274. /* **************************************************************** */  

  275. /*                                                                  */  

  276. /*                       FileMan Commands                           */  

  277. /*                                                                  */  

  278. /* **************************************************************** */  

  279.   

  280. /* String to pass to system ().  This is for the LIST, VIEW and RENAME  

  281.  commands. */  

  282. static char syscom[1024];   

  283.   

  284. /* List the file(s) named in arg. */  

  285. int com_list(char *arg) {   

  286.     if (!arg)   

  287.         arg = “”;   

  288.   

  289.     sprintf(syscom, “ls -FClg %s”, arg);   

  290.     return (system(syscom));   

  291. }   

  292.   

  293. int com_view(char *arg) {   

  294.     if (!valid_argument(“view”, arg))   

  295.         return 1;   

  296.   

  297.     sprintf(syscom, “more %s”, arg);   

  298.     return (system(syscom));   

  299. }   

  300.   

  301. int com_history(char* arg) {   

  302.     HIST_ENTRY *he;   

  303.   

  304.     /* rewind history */  

  305.     while (next_history())   

  306.         ;   

  307.   

  308.     for (he = current_history(); he != NULL; he = previous_history()) {   

  309.         //printf(“%5d  %s\n”, *((int*)he->data) – 1, he->line);   

  310.         printf(“%s\n”, he->line);   

  311.     }   

  312.   

  313.     return 0;   

  314. }   

  315.   

  316. int com_rename(char *arg) {   

  317.     too_dangerous(“rename”);   

  318.     return (1);   

  319. }   

  320.   

  321. int com_stat(char *arg) {   

  322.     struct stat finfo;   

  323.   

  324.     if (!valid_argument(“stat”, arg))   

  325.         return (1);   

  326.   

  327.     if (stat(arg, &finfo) == -1) {   

  328.         perror(arg);   

  329.         return (1);   

  330.     }   

  331.   

  332.     printf(“Statistics for `%s’:\n”, arg);   

  333.   

  334.     printf(“%s has %ld link%s, and is %lld byte%s in length.\n”, arg,   

  335.             (long) finfo.st_nlink, (finfo.st_nlink == 1) ? “” : “s”,   

  336.             (long long) finfo.st_size, (finfo.st_size == 1) ? “” : “s”);   

  337.     printf(“Inode Last Change at: %s”, ctime(&finfo.st_ctime));   

  338.     printf(”      Last access at: %s”, ctime(&finfo.st_atime));   

  339.     printf(”    Last modified at: %s”, ctime(&finfo.st_mtime));   

  340.     return (0);   

  341. }   

  342.   

  343. int com_delete(char *arg) {   

  344.     too_dangerous(“delete”);   

  345.     return (1);   

  346. }   

  347.   

  348. /* Print out help for ARG, or for all of the commands if ARG is  

  349.  not present. */  

  350. int com_help(char *arg) {   

  351.     register int i;   

  352.     int printed = 0;   

  353.   

  354.     for (i = 0; commands[i].name; i++) {   

  355.         if (!*arg || (strcmp(arg, commands[i].name) == 0)) {   

  356.             printf(“%s\t\t%s.\n”, commands[i].name, commands[i].doc);   

  357.             printed++;   

  358.         }   

  359.     }   

  360.   

  361.     if (!printed) {   

  362.         printf(“No commands match `%s’.  Possibilties are:\n”, arg);   

  363.   

  364.         for (i = 0; commands[i].name; i++) {   

  365.             /* Print in six columns. */  

  366.             if (printed == 6) {   

  367.                 printed = 0;   

  368.                 printf(“\n”);   

  369.             }   

  370.   

  371.             printf(“%s\t”, commands[i].name);   

  372.             printed++;   

  373.         }   

  374.   

  375.         if (printed)   

  376.             printf(“\n”);   

  377.     }   

  378.     return (0);   

  379. }   

  380.   

  381. /* Change to the directory ARG. */  

  382. int com_cd(char *arg) {   

  383.     if (chdir(arg) == -1) {   

  384.         perror(arg);   

  385.         return 1;   

  386.     }   

  387.   

  388.     com_pwd(“”);   

  389.     return (0);   

  390. }   

  391.   

  392. /* Print out the current working directory. */  

  393. int com_pwd(char* ignore) {   

  394.     char dir[1024], *s;   

  395.   

  396.     s = (char*) getcwd(dir, sizeof(dir) – 1);   

  397.     if (s == 0) {   

  398.         printf(“Error getting pwd: %s\n”, dir);   

  399.         return 1;   

  400.     }   

  401.   

  402.     printf(“Current directory is %s\n”, dir);   

  403.     return 0;   

  404. }   

  405.   

  406. /* The user wishes to quit using this program.  Just set DONE  

  407.  non-zero. */  

  408. int com_quit(char *arg) {   

  409.     done = 1;   

  410.     return (0);   

  411. }   

  412.   

  413. /* Function which tells you that you can’t do this. */  

  414. void too_dangerous(char *caller) {   

  415.     fprintf(stderr, “%s: Too dangerous for me to distribute.\n”, caller);   

  416.     fprintf(stderr, “Write it yourself.\n”);   

  417. }   

  418.   

  419. /* Return non-zero if ARG is a valid argument for CALLER,  

  420.  else print an error message and return zero. */  

  421. int valid_argument(char *caller, char *arg) {   

  422.     if (!arg || !*arg) {   

  423.         fprintf(stderr, “%s: Argument required.\n”, caller);   

  424.         return (0);   

  425.     }   

  426.   

  427.     return (1);   

  428. }   

  429.   

  430. void *   

  431. xmalloc(size_t size) {   

  432.     register void *value = (void*) malloc(size);   

  433.     if (value == 0)   

  434.         fprintf(stderr, “virtual memory exhausted”);   

  435.     return value;   

  436. }  

用eclipse编译,由于eclipses不能像终端一样使用,我们可以直接到终点运行生成的程序


进行裁剪,让他只有上下键功能


  1. /* fileman.c — A tiny application which demonstrates how to use the  

  2.  GNU Readline library.  This application interactively allows users  

  3.  to manipulate files and their modes.  

  4.  

  5.  NOTE: this was taken from the GNU Readline documentation and ported  

  6.  to libedit. A commad to output the history list was added.  

  7.  

  8.  */  

  9.   

  10. #include <stdio.h>   

  11. #include <stdlib.h>   

  12. #include <unistd.h>   

  13. #include <locale.h>   

  14. #include <string.h>   

  15. #include <ctype.h>   

  16.   

  17. /* GNU readline  

  18.  #include <readline/readline.h>  

  19.  #include <readline/history.h>  

  20.  */  

  21. #include <editline/readline.h>   

  22.   

  23. void * xmalloc(size_t size);   

  24. void initialize_readline();   

  25.   

  26. /* Forward declarations. */  

  27. char *stripwhite(char *string);   

  28.   

  29. /* When non-zero, this means the user is done using this program. */  

  30.   

  31. int main(int argc, char **argv) {   

  32.     char *line, *s;   

  33.   

  34.     setlocale(LC_CTYPE, “”);   

  35.   

  36.     initialize_readline(); /* Bind our completer. */  

  37.   

  38.     stifle_history(7);   

  39.   

  40.     /* Loop reading and executing lines until the user quits. */  

  41.     while (1) {   

  42.         line = readline(“FileMan: “);   

  43.   

  44.         /* Remove leading and trailing whitespace from the line.  

  45.          Then, if there is anything left, add it to the history list  

  46.          and execute it. */  

  47.         s = stripwhite(line);   

  48.   

  49.         if (*s) {   

  50.   

  51.             char* expansion;   

  52.             int result;   

  53.   

  54.             result = history_expand(s, &expansion);   

  55.   

  56.             if (result < 0 || result == 2) {   

  57.                 fprintf(stderr, “%s\n”, expansion);   

  58.             } else {   

  59.                 add_history(expansion);   

  60.             }   

  61.             free(expansion);   

  62.         }   

  63.   

  64.         free(line);   

  65.     }   

  66.     exit(0);   

  67.   

  68.     return 0;   

  69. }   

  70.   

  71. /* Look up NAME as the name of a command, and return a pointer to that  

  72.  command.  Return a NULL pointer if NAME isn’t a command name. */  

  73.   

  74. /* Strip whitespace from the start and end of STRING.  Return a pointer  

  75.  into STRING. */  

  76. char *   

  77. stripwhite(char *string) {   

  78.     register char *s, *t;   

  79.   

  80.     for (s = string; isspace(*s); s++)   

  81.         ;   

  82.   

  83.     if (*s == 0)   

  84.         return (s);   

  85.   

  86.     t = s + strlen(s) – 1;   

  87.     while (t > s && isspace(*t))   

  88.         t–;   

  89.     *++t = ‘\0’;   

  90.   

  91.     return s;   

  92. }   

  93.   

  94. /* **************************************************************** */  

  95. /*                                                                  */  

  96. /*                  Interface to Readline Completion                */  

  97. /*                                                                  */  

  98. /* **************************************************************** */  

  99.   

  100. char *command_generator(const char *, int);   

  101. char **fileman_completion(const char *, intint);   

  102.   

  103. /* Tell the GNU Readline library how to complete.  We want to try to  

  104.  complete on command names if this is the first word in the line, or  

  105.  on filenames if not. */  

  106. void initialize_readline() {   

  107.     /* Allow conditional parsing of the ~/.inputrc file. */  

  108.     rl_readline_name = “FileMan”;   

  109.   

  110.     /* Tell the completer that we want a crack first. */  

  111.     rl_attempted_completion_function = fileman_completion;   

  112. }   

  113.   

  114. /* Attempt to complete on the contents of TEXT.  START and END  

  115.  bound the region of rl_line_buffer that contains the word to  

  116.  complete.  TEXT is the word to complete.  We can use the entire  

  117.  contents of rl_line_buffer in case we want to do some simple  

  118.  parsing.  Returnthe array of matches, or NULL if there aren’t any. */  

  119. char **   

  120. fileman_completion(const char* text, int start, int end) {   

  121.     char **matches;   

  122.   

  123.     matches = (char **) NULL;   

  124.   

  125.     /* If this word is at the start of the line, then it is a command  

  126.      to complete.  Otherwise it is the name of a file in the current  

  127.      directory. */  

  128.     if (start == 0)   

  129.         /* TODO */  

  130.         matches = completion_matches(text, command_generator);   

  131.     /* matches = rl_completion_matches (text, command_generator); */  

  132.   

  133.     return (matches);   

  134. }   

  135.   

  136. /* Generator function for command completion.  STATE lets us  

  137.  know whether to start from scratch; without any state  

  138.  (i.e. STATE == 0), then we start at the top of the list. */  

  139. char *   

  140. command_generator(const char *text, int state) {   

  141.     /* If this is a new word to complete, initialize now.  This  

  142.      includes saving the length of TEXT for efficiency, and  

  143.      initializing the index variable to 0. */  

  144.     /* If no names matched, then return NULL. */  

  145.     return ((char *) NULL);   

  146. }   

  147.   

  148. void *   

  149. xmalloc(size_t size) {   

  150.     register void *value = (void*) malloc(size);   

  151.     if (value == 0)   

  152.         fprintf(stderr, “virtual memory exhausted”);   

  153.     return value;   

  154. }  
Man Page for READLINE
NAME
readline – get a line from a user with editing


SYNOPSIS
#include <readline.h>
#include <history.h>

typedef int Function ();

char *readline (prompt)
char *prompt;

int rl_add_defun (name, function, key)
char *name;
Function *function;
int key;

int rl_bind_key (key, function)
int key;
Function *function;

int rl_unbind_key (key)
int key;

int rl_bind_key_in_map (key, function, keymap)
int key;
Function *function;
Keymap keymap;

int rl_unbind_key_in_map (key, keymap)
int key;
Keymap keymap;

int rl_macro_bind (keyseq, macro, keymap)
char *keyseq, *macro;
Keymap keymap;

int rl_variable_bind (variable, value)
char *variable, *value;

int rl_parse_and_bind (line)
char *line;

int rl_translate_keyseq (keyseq, array, len)
char *keyseq, *array;
int *len;

Function *rl_named_function (command)
char *command;

Function *rl_function_of_keyseq (keyseq, keymap, type)
char *keyseq;

Keymap keymap;
int *type;

char **rl_invoking_keyseqs (function)
Function *function;

char **rl_invoking_keyseqs_in_map (function, keymap)
Function *function;
Keymap keymap;

void rl_function_dumper (readable)
int readable;

char **rl_funmap_names ()


COPYRIGHT
Readline is Copyright (C) 1989, 1991 by  the  Free  Software
Foundation, Inc.


DESCRIPTION
readline will read a line from the terminal and  return  it,
using prompt as a prompt. If prompt is null, no prompt is
issued. The line returned is allocated with malloc(3), so
the caller must free it when finished. The line returned
has the final newline removed, so only the text of the line
remains.

readline offers editing capabilities while the user is
entering the line. By default, the line editing commands
are similar to those of emacs. A vi-style line editing
interface is also available.

In the following descriptions, keymap can be one of
emacs_keymap, emacs_meta_keymap, emacs_ctlx_keymap,
vi_insertion_keymap, or vi_movement_keymap.

rl_add_defun makes name appear as a bindable readline com-
mand, and makes function be the function called when that
command is invoked. If key is not -1, it is bound to func-
tion in the current keymap.

rl_bind_key causes key to invoke function. The binding is
made in the current keymap.

rl_unbind_key removes the binding for key in the current
keymap.

rl_bind_key_in_map makes the key entry in keymap invoke
function.

rl_unbind_key_in_map removes the binding for key in keymap
keymap.

rl_macro_bind makes keyseq insert the string macro. The
binding is performed in keymap.

rl_variable_bind sets the value of the readline variable
variable to value.

rl_parse_and_bind takes as an argument a line of the same
form as the readline startup file (see INITIALIZATION FILE
below) and executes the commands therein.

rl_translate_keyseq converts keyseq into a new string, stor-
ing the result in array. This translates control and meta
prefixes and the readline character escape sequences (see
Key Bindings below). The length of the translated sequence
is returned in *len.

rl_named_function returns the function that is executed when
the readline command command is invoked.

rl_function_of_keyseq returns the function that is executed
when keyseq is read and keymap is the current keymap. type
is set to indicate whether the return value corresponds to a
function, macro, or auxiliary keymap.

rl_invoking_keyseqs returns all of the key sequences in the
current keymap that invoke function.

rl_invoking_keyseqs_in_map returns all of the key sequences
in keymap that invoke function.

rl_function_dumper prints all of the readline functions and
their bindings to the readline output stream. If readable
is non-zero, the output is formattted so that it can be read
back in to restore the bindings.

rl_funmap_names returns an array of all known readline bind-
able function names. The array is sorted.


RETURN VALUE
readline returns the text of the line read.   A  blank  line
returns the empty string. If EOF is encountered while read-
ing a line, and the line is empty, NULL is returned. If an
EOF is read with a non-empty line, it is treated as a new-
line.

Unless otherwise stated, the other functions return 0 on
success and non-zero on failure.


NOTATION
An emacs-style notation is used to denote keystrokes.   Con-
trol keys are denoted by C-key, e.g., C-n means Control-N.
Similarly, meta keys are denoted by M-key, so M-x means

Meta-X. (On keyboards without a meta key, M-x means ESC x,
i.e., press the Escape key then the x key. This makes ESC
the meta prefix. The combination M-C-x means ESC-Control-x,
or press the Escape key then hold the Control key while
pressing the x key.)

Readline commands may be given numeric arguments, which nor-
mally act as a repeat count. Sometimes, however, it is the
sign of the argument that is significant. Passing a nega-
tive argument to a command that acts in the forward direc-
tion (e.g., kill-line) causes that command to act in a back-
ward direction. Commands whose behavior with arguments
deviates from this are noted.

When a command is described as killing text, the text
deleted is saved for possible future retrieval (yanking).
The killed text is saved in a killring. Consecutive kills
cause the text to be accumulated into one unit, which can be
yanked all at once. Commands which do not kill text separate
the chunks of text on the kill-ring.


INITIALIZATION FILE
Readline is customized by putting commands in an initializa-
tion file. The name of this file is taken from the value of
the INPUTRC variable. If that variable is unset, the
default is ~/.inputrc. When a program which uses the read-
line library starts up, the init file is read, and the key
bindings and variables are set. There are only a few basic
constructs allowed in the readline init file. Blank lines
are ignored. Lines beginning with a # are comments. Lines
beginning with a $ indicate conditional constructs. Other
lines denote key bindings and variable settings. Each pro-
gram using this library may add its own commands and bind-
ings.

For example, placing

M-Control-u: universal-argument
or
C-Meta-u: universal-argument
into the ~/.inputrc would make M-C-u execute the readline
command universalargument.

The following symbolic character names are recognized while
processing key bindings: RUBOUT, DEL, ESC, LFD, NEWLINE,
RET, RETURN, SPC, SPACE, and TAB. In addition to command
names, readline allows keys to be bound to a string that is
inserted when the key is pressed (a macro).

Key Bindings
The syntax for controlling key bindings in the ~/.inputrc
file is simple. All that is required is the name of the
command or the text of a macro and a key sequence to which
it should be bound. The name may be specified in one of two
ways: as a symbolic key name, possibly with Meta– or Con-
trol– prefixes, or as a key sequence. When using the form
keyname:functionname or macro, keyname is the name of a key
spelled out in English. For example:

Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: “>&output”

In the above example, Cu is bound to the function
universal-argument, MDEL is bound to the function
backward-kill-word, and Co is bound to run the macro
expressed on the right hand side (that is, to insert the
text >&output into the line).

In the second form, “keyseq”:functionname or macro, keyseq
differs from keyname above in that strings denoting an
entire key sequence may be specified by placing the sequence
within double quotes. Some GNU Emacs style key escapes can
be used, as in the following example.

“\C-u”: universal-argument
“\C-x\C-r”: re-read-init-file
“\e[11~”: “Function Key 1”

In this example, Cu is again bound to the function
universal-argument. Cx Cr is bound to the function
re-read-init-file, and ESC [ 1 1 ~ is bound to insert the
text Function Key 1. The full set of escape sequences is

\C- control prefix

\M- meta prefix

\e an escape character

\\ backslash

” \” literal ”

\’ literal ‘

When entering the text of a macro, single or double quotes
should be used to indicate a macro definition. Unquoted
text is assumed to be a function name. Backslash will quote
any character in the macro text, including ” and ‘.

Bash allows the current readline key bindings to be
displayed or modified with the bind builtin command. The
editing mode may be switched during interactive use by using
the -o option to the set builtin command. Other programs
using this library provide similar mechanisms. The inputrc
file may be edited and re-read if a program does not provide
any other means to incorporate new bindings.

Variables
Readline has variables that can be used to further customize
its behavior. A variable may be set in the inputrc file
with a statement of the form

set variablename value

Except where noted, readline variables can take the values
On or Off. The variables and their default values are:

horizontal-scroll-mode (Off)
When set to On, makes readline use a single line for
display, scrolling the input horizontally on a single
screen line when it becomes longer than the screen
width rather than wrapping to a new line.
editing-mode (emacs)
Controls whether readline begins with a set of key
bindings similar to emacs or vi. editing-mode can be
set to either emacs or vi.
mark-modified-lines (Off)
If set to On, history lines that have been modified are
displayed with a preceding asterisk (*).
bell-style (audible)
Controls what happens when readline wants to ring the
terminal bell. If set to none, readline never rings
the bell. If set to visible, readline uses a visible
bell if one is available. If set to audible, readline
attempts to ring the terminal’s bell.
comment-begin (“#”)
The string that is inserted in vi mode when the
vi-comment command is executed.
meta-flag (Off)
If set to On, readline will enable eight-bit input
(that is, it will not strip the high bit from the char-
acters it reads), regardless of what the terminal
claims it can support.
convert-meta (On)
If set to On, readline will convert characters with the
eighth bit set to an ASCII key sequence by stripping
the eighth bit and prepending an escape character (in
effect, using escape as the meta prefix).
output-meta (Off)
If set to On, readline will display characters with the
eighth bit set directly rather than as a meta-prefixed
escape sequence.
completion-query-items (100)
This determines when the user is queried about viewing

the number of possible completions generated by the
possible-completions command. It may be set to any
integer value greater than or equal to zero. If the
number of possible completions is greater than or equal
to the value of this variable, the user is asked
whether or not he wishes to view them; otherwise they
are simply listed on the terminal.
keymap (emacs)
Set the current readline keymap. The set of legal key-
map names is emacs, emacsstandard, emacsmeta, emacs
ctlx, vi, vimove, vicommand, and viinsert. vi is
equivalent to vicommand; emacs is equivalent to
emacsstandard. The default value is emacs; the value
of editing-mode also affects the default keymap.
show-all-if-ambiguous (Off)
This alters the default behavior of the completion
functions. If set to on, words which have more than
one possible completion cause the matches to be listed
immediately instead of ringing the bell.
expand-tilde (Off)
If set to on, tilde expansion is performed when read-
line attempts word completion.

Conditional Constructs
Readline implements a facility similar in spirit to the con-
ditional compilation features of the C preprocessor which
allows key bindings and variable settings to be performed as
the result of tests. There are three parser directives
used.

$if The $if construct allows bindings to be made based on
the editing mode, the terminal being used, or the
application using readline. The text of the test
extends to the end of the line; no characters are
required to isolate it.

mode The mode= form of the $if directive is used to
test whether readline is in emacs or vi mode.
This may be used in conjunction with the set key-
map command, for instance, to set bindings in the
emacsstandard and emacsctlx keymaps only if
readline is starting out in emacs mode.

term The term= form may be used to include terminal-
specific key bindings, perhaps to bind the key
sequences output by the terminal’s function keys.
The word on the right side of the = is tested
against the full name of the terminal and the por-
tion of the terminal name before the first -.
This allows sun to match both sun and suncmd, for
instance.

application
The application construct is used to include
application-specific settings. Each program using
the readline library sets the application name,
and an initialization file can test for a particu-
lar value. This could be used to bind key
sequences to functions useful for a specific pro-
gram. For instance, the following command adds a
key sequence that quotes the current or previous
word in Bash:
$if bash
# Quote the current or previous word
“\C-xq”: “\eb\”\ef\””
$endif

$endif
This command, as you saw in the previous example, ter-
minates an $if command.

$else
Commands in this branch of the $if directive are exe-
cuted if the test fails.


EDITING COMMANDS
The following is a list of the names of the commands and the
default key sequences to which they are bound.

Commands for Moving
beginning-of-line (C-a)
Move to the start of the current line.
end-of-line (C-e)
Move to the end of the line.
forward-char (C-f)
Move forward a character.
backward-char (C-b)
Move back a character.
forward-word (M-f)
Move forward to the end of the next word. Words are
composed of alphanumeric characters (letters and
digits).
backward-word (M-b)
Move back to the start of this, or the previous, word.
Words are composed of alphanumeric characters (letters
and digits).
clear-screen (C-l)
Clear the screen leaving the current line at the top of
the screen. With an argument, refresh the current line
without clearing the screen.
redraw-current-line
Refresh the current line. By default, this is unbound.

Commands for Manipulating the History
accept-line (Newline, Return)
Accept the line regardless of where the cursor is. If
this line is non-empty, add it to the history list. If
the line is a modified history line, then restore the
history line to its original state.
previous-history (C-p)
Fetch the previous command from the history list, mov-
ing back in the list.
next-history (C-n)
Fetch the next command from the history list, moving
forward in the list.
beginning-of-history (M-<)
Move to the first line in the history.
end-of-history (M->)
Move to the end of the input history, i.e., the line
currently being entered.
reverse-search-history (C-r)
Search backward starting at the current line and moving
`up’ through the history as necessary. This is an
incremental search.
forward-search-history (C-s)
Search forward starting at the current line and moving
`down’ through the history as necessary. This is an
incremental search.
non-incremental-reverse-search-history (M-p)
Search backward through the history starting at the
current line using a non-incremental search for a
string supplied by the user.
non-incremental-forward-search-history (M-n)
Search forward through the history using a
non-incremental search for a string supplied by the
user.
history-search-forward
Search forward through the history for the string of
characters between the start of the current line and
the current point. This is a non-incremental search.
By default, this command is unbound.
history-search-backward
Search backward through the history for the string of
characters between the start of the current line and
the current point. This is a non-incremental search.
By default, this command is unbound.
yank-nth-arg (M-C-y)
Insert the first argument to the previous command (usu-
ally the second word on the previous line) at point
(the current cursor position). With an argument n,
insert the nth word from the previous command (the
words in the previous command begin with word 0). A
negative argument inserts the nth word from the end of
the previous command.
yank-last-arg (M-., M-_)

Insert the last argument to the previous command (the
last word on the previous line). With an argument,
behave exactly like yank-nth-arg.

Commands for Changing Text
delete-char (C-d)
Delete the character under the cursor. If point is at
the beginning of the line, there are no characters in
the line, and the last character typed was not C-d,
then return EOF.
backward-delete-char (Rubout)
Delete the character behind the cursor. When given a
numeric argument, save the deleted text on the
kill-ring.
quoted-insert (C-q, C-v)
Add the next character that you type to the line verba-
tim. This is how to insert characters like C-q, for
example.
tab-insert (M-TAB)
Insert a tab character.
self-insert (a, b, A, 1, !, …)
Insert the character typed.
transpose-chars (C-t)
Drag the character before point forward over the char-
acter at point. Point moves forward as well. If point
is at the end of the line, then transpose the two char-
acters before point. Negative arguments don’t work.
transpose-words (M-t)
Drag the word behind the cursor past the word in front
of the cursor moving the cursor over that word as well.
upcase-word (M-u)
Uppercase the current (or following) word. With a
negative argument, do the previous word, but do not
move point.
downcase-word (M-l)
Lowercase the current (or following) word. With a
negative argument, do the previous word, but do not
move point.
capitalize-word (M-c)
Capitalize the current (or following) word. With a
negative argument, do the previous word, but do not
move point.

Killing and Yanking
kill-line (C-k)
Kill the text from the current cursor position to the
end of the line.
backward-kill-line (C-x Rubout)
Kill backward to the beginning of the line.
unix-line-discard (C-u)
Kill backward from point to the beginning of the line.
kill-whole-line

Kill all characters on the current line, no matter
where the cursor is. By default, this is unbound.
kill-word (M-d)
Kill from the cursor to the end of the current word, or
if between words, to the end of the next word. Word
boundaries are the same as those used by forward-word.
backward-kill-word (M-Rubout)
Kill the word behind the cursor. Word boundaries are
the same as those used by backward-word.
unix-word-rubout (C-w)
Kill the word behind the cursor, using white space as a
word boundary. The word boundaries are different from
backward-kill-word.
delete-horizontal-space
Delete all spaces and tabs around point. By default,
this is unbound.
yank (C-y)
Yank the top of the kill ring into the buffer at the
cursor.
yank-pop (M-y)
Rotate the kill-ring, and yank the new top. Only works
following yank or yank-pop.

Numeric Arguments
digit-argument (M-0, M-1, …, M–)
Add this digit to the argument already accumulating, or
start a new argument. M– starts a negative argument.
universal-argument
Each time this is executed, the argument count is mul-
tiplied by four. The argument count is initially one,
so executing this function the first time makes the
argument count four. By default, this is not bound to
a key.

Completing
complete (TAB)
Attempt to perform completion on the text before point.
The actual completion performed is application-
specific. Bash, for instance, attempts completion
treating the text as a variable (if the text begins
with $), username (if the text begins with ~), hostname
(if the text begins with @), or command (including
aliases and functions) in turn. If none of these pro-
duces a match, filename completion is attempted. Gdb,
on the other hand, allows completion of program func-
tions and variables, and only attempts filename comple-
tion under certain circumstances.
possible-completions (M-?)
List the possible completions of the text before point.
insert-completions
Insert all completions of the text before point that
would have been generated by possible-completions. By

default, this is not bound to a key.

Keyboard Macros
start-kbd-macro (C-x ()
Begin saving the characters typed into the current key-
board macro.
end-kbd-macro (C-x ))
Stop saving the characters typed into the current key-
board macro and save the definition.
call-last-kbd-macro (C-x e)
Re-execute the last keyboard macro defined, by making
the characters in the macro appear as if typed at the
keyboard.

Miscellaneous
re-read-init-file (C-x C-r)
Read in the contents of your init file, and incorporate
any bindings or variable assignments found there.
abort (C-g)
Abort the current editing command and ring the
terminal’s bell (subject to the setting of bell-style).
do-uppercase-version (M-a, M-b, …)
Run the command that is bound to the corresponding
uppercase character.
prefix-meta (ESC)
Metafy the next character typed. ESC f is equivalent
to Meta-f.
undo (C-_, C-x C-u)
Incremental undo, separately remembered for each line.
revert-line (M-r)
Undo all changes made to this line. This is like typ-
ing the undo command enough times to return the line to
its initial state.
tilde-expand (M-~)
Perform tilde expansion on the current word.
dump-functions
Print all of the functions and their key bindings to
the readline output stream. If a numeric argument is
supplied, the output is formatted in such a way that it
can be made part of an inputrc file.
emacs-editing-mode (C-e)
When in vi editing mode, this causes a switch to emacs
editing mode.
vi-editing-mode (M-C-j)
When in emacs editing mode, this causes a switch to vi
editing mode.


DEFAULT KEY BINDINGS
The following is a list of the default emacs  and  vi  bind-
ings. Characters with the 8th bit set are written as M-
<character>, and are referred to as metafied characters.
The printable ASCII characters not mentioned in the list of

emacs standard bindings are bound to the selfinsert func-
tion, which just inserts the given character into the input
line. In vi insertion mode, all characters not specifically
mentioned are bound to selfinsert. Characters assigned to
signal generation by stty(1) or the terminal driver, such as
C-Z or C-C, retain that function. Upper and lower case
metafied characters are bound to the same function in the
emacs mode meta keymap. The remaining characters are
unbound, which causes readline to ring the bell (subject to
the setting of the bell-style variable).

Emacs Mode
Emacs Standard bindings

“C-A” -> beginning-of-line
“C-B” -> backward-char
“C-D” -> delete-char
“C-E” -> end-of-line
“C-F” -> forward-char
“C-G” -> abort
“C-H” -> backward-delete-char
“C-I” -> complete
“C-J” -> accept-line
“C-K” -> kill-line
“C-L” -> clear-screen
“C-M” -> accept-line
“C-N” -> next-history
“C-P” -> previous-history
“C-Q” -> quoted-insert
“C-R” -> reverse-search-history
“C-S” -> forward-search-history
“C-T” -> transpose-chars
“C-U” -> unix-line-discard
“C-V” -> quoted-insert
“C-W” -> unix-word-rubout
“C-Y” -> yank
“C-_” -> undo
” ” to “/” -> self-insert
“0” to “9” -> self-insert
“:” to “~” -> self-insert
“C-?” -> backward-delete-char

Emacs Meta bindings

“M-C-H” -> backward-kill-word
“M-C-I” -> tab-insert
“M-C-J” -> vi-editing-mode
“M-C-M” -> vi-editing-mode
“M-C-R” -> revert-line
“M-C-Y” -> yank-nth-arg
“M-C-[” -> complete
“M-&” -> tilde-expand

“M–” -> digit-argument
“M-0” -> digit-argument
“M-1” -> digit-argument
“M-2” -> digit-argument
“M-3” -> digit-argument
“M-4” -> digit-argument
“M-5” -> digit-argument
“M-6” -> digit-argument
“M-7” -> digit-argument
“M-8” -> digit-argument
“M-9” -> digit-argument
“M-<” -> beginning-of-history
“M->” -> end-of-history
“M-?” -> possible-completions
“M-B” -> backward-word
“M-C” -> capitalize-word
“M-D” -> kill-word
“M-F” -> forward-word
“M-L” -> downcase-word
“M-N” -> non-incremental-forward-search-history
“M-O” -> arrow-key-prefix
“M-P” -> non-incremental-reverse-search-history
“M-R” -> revert-line
“M-T” -> transpose-words
“M-U” -> upcase-word
“M-Y” -> yank-pop
“M-C-Y” -> yank-nth-arg
“M-C-?” -> backward-delete-word

Emacs Control-X bindings

“C-XC-G” -> abort
“C-XC-R” -> re-read-init-file
“C-XC-U” -> undo
“C-X(” -> start-kbd-macro
“C-X)” -> end-kbd-macro
“C-Xe” -> call-last-kbd-macro
“C-XC-?” -> backward-kill-line

VI Mode bindings
VI Insert Mode functions

“C-D” -> vi-eof-maybe
“C-H” -> backward-delete-char
“C-I” -> complete
“C-J” -> accept-line
“C-K” -> kill-line
“C-L” -> clear-screen
“C-M” -> accept-line
“C-N” -> next-history
“C-P” -> previous-history

“C-Q” -> quoted-insert
“C-R” -> reverse-search-history
“C-S” -> forward-search-history
“C-T” -> transpose-chars
“C-U” -> unix-line-discard
“C-V” -> quoted-insert
“C-W” -> unix-word-rubout
“C-Y” -> yank
“C-[” -> vi-movement-mode
” ” to “~” -> self-insert
“C-?” -> backward-delete-char

VI Command Mode functions

“C-D” -> vi-eof-maybe
“C-E” -> emacs-editing-mode
“C-G” -> abort
“C-H” -> backward-char
“C-J” -> accept-line
“C-K” -> kill-line
“C-L” -> clear-screen
“C-M” -> accept-line
“C-N” -> next-history
“C-P” -> previous-history
“C-Q” -> quoted-insert
“C-R” -> reverse-search-history
“C-S” -> forward-search-history
“C-T” -> transpose-chars
“C-U” -> unix-line-discard
“C-V” -> quoted-insert
“C-W” -> unix-word-rubout
“C-Y” -> yank
“C-[” -> abort
” ” -> forward-char
“#” -> vi-comment
“$” -> end-of-line
“%” -> vi-match
“&” -> vi-tilde-expand
“*” -> vi-complete
“+” -> down-history
“,” -> vi-char-search
“-” -> previous-history
“.” -> vi-redo
“/” -> vi-search
“0” -> beginning-of-line
“1” to “9” -> vi-arg-digit
“;” -> vi-char-search
“=” -> vi-complete
“?” -> vi-search
“@” -> is undefined
“A” -> vi-append-eol
“B” -> vi-prev-word

“C” -> vi-change-to
“D” -> vi-delete-to
“E” -> vi-end-word
“F” -> vi-char-search
“I” -> vi-insert-beg
“N” -> vi-search-again
“P” -> vi-put
“R” -> vi-replace
“S” -> vi-subst
“T” -> vi-char-search
“U” -> revert-line
“W” -> vi-next-word
“X” -> backward-delete-char
“Y” -> vi-yank-to
“\” -> vi-complete
“^” -> vi-first-print
“_” -> vi-yank-arg
“a” -> vi-append-mode
“b” -> vi-prev-word
“c” -> vi-change-to
“d” -> vi-delete-to
“e” -> vi-end-word
“f” -> vi-char-search
“h” -> backward-char
“i” -> vi-insertion-mode
“j” -> next-history
“k” -> prev-history
“l” -> forward-char
“n” -> vi-search-again
“r” -> vi-change-char
“s” -> vi-subst
“t” -> vi-char-search
“u” -> undo
“w” -> vi-next-word
“x” -> vi-delete
“y” -> vi-yank-to
“|” -> vi-column
“~” -> vi-change-case


SEE ALSO
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)


FILES
~/.inputrc
Individual readline initialization file


AUTHORS
Brian Fox, Free Software Foundation (primary author)


Bfox@MIT.Edu

Chet Ramey, Case Western Reserve University


Chet@CWRU.Edu


BUG REPORTS
If you find a bug in readline, you should  report  it.   But
first, you should make sure that it really is a bug, and
that it appears in the latest version of the readline
library that you have.

Once you have determined that a bug actually exists, mail a
bug report to bashmaintainers@prep.ai.MIT.Edu. If you have
a fix, you are welcome to mail that as well! Suggestions
and `philosophical’ bug reports may be mailed to bug
bash@prep.ai.MIT.Edu or posted to the Usenet newsgroup
gnu.bash.bug.

Comments and bug reports concerning this manual page should
be directed to chet@ins.CWRU.Edu.


BUGS
It’s too big and too slow.

赞(0) 打赏
转载请注明出处:服务器评测 » 实现Linux下上下键和命令补全
分享到: 更多 (0)

听说打赏我的人,都进福布斯排行榜啦!

支付宝扫一扫打赏

微信扫一扫打赏