diff options
| author | 2024-09-04 15:41:08 -0400 | |
|---|---|---|
| committer | 2024-09-04 15:41:08 -0400 | |
| commit | e828e256f19446bd3095e91211a828909826c731 (patch) | |
| tree | 4637f1e6bf520a19c0cfcc6a04e59f4571092978 | |
| parent | history saving implemented (diff) | |
command history scrolling implemented
| -rw-r--r-- | src/history.c | 3 | ||||
| -rw-r--r-- | src/lush.c | 32 |
2 files changed, 34 insertions, 1 deletions
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 } @@ -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; } } } |
