From e828e256f19446bd3095e91211a828909826c731 Mon Sep 17 00:00:00 2001 From: BanceDev Date: Wed, 4 Sep 2024 15:41:08 -0400 Subject: command history scrolling implemented --- src/history.c | 3 ++- src/lush.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/history.c b/src/history.c index 028745e..511f12a 100644 --- a/src/history.c +++ b/src/history.c @@ -151,7 +151,8 @@ void lush_push_history(const char *line) { fprintf(fp, "%s\n", line); // Write the last MAX_LINES lines - for (int i = 0; i < MAX_LINES; i++) { + int total_lines = line_count < MAX_LINES ? line_count : MAX_LINES; + for (int i = 0; i < total_lines; i++) { fprintf(fp, "%s", lines[i]); free(lines[i]); // Free each line after writing } diff --git a/src/lush.c b/src/lush.c index 81f9e64..63589d8 100644 --- a/src/lush.c +++ b/src/lush.c @@ -202,6 +202,7 @@ char *lush_read_line() { struct termios orig_termios; char *buffer = (char *)calloc(BUFFER_SIZE, sizeof(char)); int pos = 0; + int history_pos = 0; int c; // init buffer and make raw mode @@ -213,6 +214,29 @@ char *lush_read_line() { if (c == '\033') { // escape sequence getchar(); // skip [ switch (getchar()) { + case 'A': // up arrow + { + char *history_line = lush_get_past_command(history_pos); + strncpy(buffer, history_line, BUFFER_SIZE); + free(history_line); + // remove newline from buffer + buffer[strlen(buffer) - 1] = '\0'; + pos = strlen(buffer); + reprint_buffer(buffer, pos); + history_pos++; + } break; + case 'B': // down arrow + { + char *history_line = lush_get_past_command(history_pos); + strncpy(buffer, history_line, BUFFER_SIZE); + free(history_line); + // remove newline from buffer + buffer[strlen(buffer) - 1] = '\0'; + pos = strlen(buffer); + reprint_buffer(buffer, pos); + if (history_pos > 0) + history_pos--; + } break; case 'C': // right arrow if (pos < strlen(buffer)) { pos++; @@ -233,6 +257,8 @@ char *lush_read_line() { reprint_buffer(buffer, pos); } } + // if modifying text reset history + history_pos = 0; break; default: break; @@ -244,7 +270,11 @@ char *lush_read_line() { pos--; reprint_buffer(buffer, pos); } + // if modifying text reset history + history_pos = 0; } else if (c == '\n') { + // if modifying text reset history + history_pos = 0; break; // submit the command } else { if (pos < BUFFER_SIZE - 1) { @@ -255,6 +285,8 @@ char *lush_read_line() { pos++; reprint_buffer(buffer, pos); + // if modifying text reset history + history_pos = 0; } } } -- cgit v1.2.3-59-g8ed1b