From ba3fc967be74d016a901a9ce23802fd51f69dd7e Mon Sep 17 00:00:00 2001 From: Aaron Fischer Date: Mon, 8 Oct 2018 15:34:52 +0200 Subject: [PATCH] Finish the editor features --- kilo.c | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/kilo.c b/kilo.c index bee0c25..f7820a2 100644 --- a/kilo.c +++ b/kilo.c @@ -69,6 +69,8 @@ struct editorConfig E; /*** prototypes ***/ void editorSetStatusMessage(const char *fmt, ...); +void editorRefreshScreen(); +char *editorPrompt(char *prompt); /*** terminal ***/ @@ -370,7 +372,13 @@ void editorOpen(char *filename) { } void editorSave() { - if (E.filename == NULL) return; + if (E.filename == NULL) { + E.filename = editorPrompt("Save as: %s (ESC to cancel)"); + if (E.filename == NULL) { + editorSetStatusMessage("Save aborted"); + return; + } + } int len; char *buf = editorRowsToString(&len); @@ -531,6 +539,40 @@ void editorSetStatusMessage(const char *fmt, ...) { /*** input ***/ +char *editorPrompt(char *prompt) { + size_t bufsize = 128; + char *buf = malloc(bufsize); + + size_t buflen = 0; + buf[0] = '\0'; + + while (1) { + editorSetStatusMessage(prompt, buf); + editorRefreshScreen(); + + int c = editorReadKey(); + if (c == DEL_KEY || c == CTRL_KEY('h') || c == BACKSPACE) { + if (buflen != 0) buf[--buflen] = '\0'; + } else if (c == '\x1b') { + editorSetStatusMessage(""); + free(buf); + return NULL; + } else if (c == '\r') { + if (buflen != 0) { + editorSetStatusMessage(""); + return buf; + } + } else if (!iscntrl(c) && c < 128) { + if (buflen == bufsize -1) { + bufsize *= 2; + buf = realloc(buf, bufsize); + } + buf[buflen++] = c; + buf[buflen] = '\0'; + } + } +} + void editorMoveCursor(int key) { erow *row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy];