From 827be306efe6d15d3213b272b564196e96f34640 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Tue, 20 Aug 2019 13:39:30 -0400 Subject: [PATCH] Save as functionality --- kilo.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/kilo.c b/kilo.c index 6a0ecac..1dd38dd 100644 --- a/kilo.c +++ b/kilo.c @@ -68,6 +68,8 @@ struct editorConfig E; /*** prototypes ***/ void editorSetStatusMessage(const char *fmt, ...); +void editorRefreshScreen(); +char *editorPrompt(char *prompt); /*** terminal ***/ @@ -499,7 +501,12 @@ void editorSave() { if (E.filename == NULL) { - return; + E.filename = editorPrompt("Save as: %s (ESC to cancel)"); + if (E.filename == NULL) + { + editorSetStatusMessage("Save aborted"); + return; + } } int len; @@ -728,6 +735,54 @@ 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];