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