Example app improved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
diff --git a/example.c b/example.c
index c4d12e7..5fdc9d1 100644
--- a/example.c
+++ b/example.c
@@ -15,6 +15,7 @@ int main(int argc, char **argv) {
char *line;
char *prgname = argv[0];
+ /* Parse options, with --multiline we enable multi line editing. */
while(argc > 1) {
argc--;
argv++;
@@ -27,13 +28,32 @@ int main(int argc, char **argv) {
}
}
+ /* Set the completion callback. This will be called every time the
+ * user uses the <tab> key. */
linenoiseSetCompletionCallback(completion);
+
+ /* Load history from file. The history file is just a plain text file
+ * where entries are separated by newlines. */
linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
+
+ /* Now this is the main loop of the typical linenoise-based application.
+ * The call to linenoise() will block as long as the user types something
+ * and presses enter.
+ *
+ * The typed string is returned as a malloc() allocated string by
+ * linenoise, so the user needs to free() it. */
while((line = linenoise("hello> ")) != NULL) {
- if (line[0] != '\0') {
+ /* Do something with the string. */
+ if (line[0] != '\0' && line[0] != '/') {
printf("echo: '%s'\n", line);
- linenoiseHistoryAdd(line);
- linenoiseHistorySave("history.txt"); /* Save every new entry */
+ linenoiseHistoryAdd(line); /* Add to the history. */
+ linenoiseHistorySave("history.txt"); /* Save the history on disk. */
+ } else if (!strncmp(line,"/historylen",11)) {
+ /* The "/historylen" command will change the history len. */
+ int len = atoi(line+11);
+ linenoiseHistorySetMaxLen(len);
+ } else if (line[0] == '/') {
+ printf("Unreconized command: %s\n", line);
}
free(line);
}