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