1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "linenoise.h"
5 
6 
completion(const char * buf,linenoiseCompletions * lc)7 void completion(const char *buf, linenoiseCompletions *lc) {
8     if (buf[0] == 'h') {
9         linenoiseAddCompletion(lc,"hello");
10         linenoiseAddCompletion(lc,"hello there");
11     }
12 }
13 
main(int argc,char ** argv)14 int main(int argc, char **argv) {
15     char *line;
16     char *prgname = argv[0];
17 
18     /* Parse options, with --multiline we enable multi line editing. */
19     while(argc > 1) {
20         argc--;
21         argv++;
22         if (!strcmp(*argv,"--multiline")) {
23             linenoiseSetMultiLine(1);
24             printf("Multi-line mode enabled.\n");
25         } else if (!strcmp(*argv,"--keycodes")) {
26             linenoisePrintKeyCodes();
27             exit(0);
28         } else {
29             fprintf(stderr, "Usage: %s [--multiline] [--keycodes]\n", prgname);
30             exit(1);
31         }
32     }
33 
34     /* Set the completion callback. This will be called every time the
35      * user uses the <tab> key. */
36     linenoiseSetCompletionCallback(completion);
37 
38     /* Load history from file. The history file is just a plain text file
39      * where entries are separated by newlines. */
40     linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
41 
42     /* Now this is the main loop of the typical linenoise-based application.
43      * The call to linenoise() will block as long as the user types something
44      * and presses enter.
45      *
46      * The typed string is returned as a malloc() allocated string by
47      * linenoise, so the user needs to free() it. */
48     while((line = linenoise("hello> ")) != NULL) {
49         /* Do something with the string. */
50         if (line[0] != '\0' && line[0] != '/') {
51             printf("echo: '%s'\n", line);
52             linenoiseHistoryAdd(line); /* Add to the history. */
53             linenoiseHistorySave("history.txt"); /* Save the history on disk. */
54         } else if (!strncmp(line,"/historylen",11)) {
55             /* The "/historylen" command will change the history len. */
56             int len = atoi(line+11);
57             linenoiseHistorySetMaxLen(len);
58         } else if (line[0] == '/') {
59             printf("Unreconized command: %s\n", line);
60         }
61         free(line);
62     }
63     return 0;
64 }
65