]> git.lizzy.rs Git - linenoise.git/commitdiff
Example app improved.
authorantirez <antirez@gmail.com>
Fri, 8 Feb 2013 11:24:07 +0000 (12:24 +0100)
committerSteve Bennett <steveb@workware.net.au>
Tue, 26 Feb 2013 04:10:48 +0000 (14:10 +1000)
example.c

index cb51a0af8f9259eca7504261e63bb35627f3cc5c..b436ed313be8db96b991396807a0c424f168e1fe 100644 (file)
--- a/example.c
+++ b/example.c
@@ -1,5 +1,6 @@
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include "linenoise.h"
 
 #ifndef NO_COMPLETION
@@ -11,18 +12,54 @@ void completion(const char *buf, linenoiseCompletions *lc) {
 }
 #endif
 
-int main(void) {
+int main(int argc, char *argv[]) {
     char *line;
+#ifdef HAVE_MULTILINE
+    /* Note: multiline support has not yet been integrated */
+    char *prgname = argv[0];
+
+    /* Parse options, with --multiline we enable multi line editing. */
+    while(argc > 1) {
+        argc--;
+        argv++;
+        if (!strcmp(*argv,"--multiline")) {
+            linenoiseSetMultiLine(1);
+            printf("Multi-line mode enabled.\n");
+        } else {
+            fprintf(stderr, "Usage: %s [--multiline]\n", prgname);
+            exit(1);
+        }
+    }
+#endif
 
 #ifndef NO_COMPLETION
+    /* Set the completion callback. This will be called every time the
+     * user uses the <tab> key. */
     linenoiseSetCompletionCallback(completion);
 #endif
+
+    /* 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);
     }