diff --git a/include/slash/slash.h b/include/slash/slash.h index f4c69ac..7c7a3c3 100644 --- a/include/slash/slash.h +++ b/include/slash/slash.h @@ -26,6 +26,7 @@ #include #include +#include #include @@ -161,7 +162,7 @@ struct slash { char *history_head; char *history_tail; char *history_cursor; - + FILE *history_file; /* Command interface */ char **argv; int argc; @@ -239,6 +240,13 @@ void slash_command_description(struct slash *slash, struct slash_command *comman int slash_run(struct slash *slash, char * filename, int printcmd); +/** + * @brief Populate Slash history buffer with the content of the given file + * @param slash pointer to valid slash context + * @param history_filename filename to use (will be created if it doesn't exist) to read and write history + */ +void slash_init_history_from_file(struct slash *slash, const char *history_filename); + void slash_history_add(struct slash *slash, char *line); typedef struct slash_list_iterator_s { diff --git a/src/slash.c b/src/slash.c index 87930c2..5b8078f 100644 --- a/src/slash.c +++ b/src/slash.c @@ -568,8 +568,13 @@ void slash_history_add(struct slash *slash, char *line) return; /* Push including trailing zero */ - if (!slash_line_empty(line, strlen(line))) + if (!slash_line_empty(line, strlen(line))) { + if(slash->history_file) { + fprintf(slash->history_file, "%s\n", line); + fflush(slash->history_file); + } slash_history_push(slash, line, strlen(line) + 1); + } } static void slash_history_next(struct slash *slash) @@ -1056,3 +1061,22 @@ void slash_destroy(struct slash *slash) free(slash); } + +void slash_init_history_from_file(struct slash *slash, const char *history_filename) { + /* Set this to NULL to disable history, will be set if all goes well */ + slash->history_file = NULL; + FILE *history = fopen(history_filename, "a+"); + if (history) { + ssize_t read; + char *line; + size_t len = 0; + while ((read = getline(&line, &len, history)) != -1) { + if(line[read - 1] == '\n') { + line[read - 1] = '\0'; + } + slash_history_add(slash, line); + } + free(line); + slash->history_file = history; + } +}