Add dirty flag

This commit is contained in:
Aaron Fischer 2018-10-05 11:59:27 +02:00
parent 1abad8b71f
commit 01615ba5ef

22
kilo.c
View file

@ -21,6 +21,7 @@
#define KILO_VERSION "0.0.1"
#define KILO_TAB_STOP 8
#define KILO_QUIT_TIMES 3
#define CTRL_KEY(k) ((k) & 0x1f)
@ -56,6 +57,7 @@ struct editorConfig {
int screencols;
int numrows;
erow *row;
int dirty;
char *filename;
char statusmsg[80];
time_t statusmsg_time;
@ -236,6 +238,7 @@ void editorAppendRow(char *s, size_t len) {
editorUpdateRow(&E.row[at]);
E.numrows++;
E.dirty++;
}
void editorRowInsertChar(erow *row, int at, int c) {
@ -245,6 +248,7 @@ void editorRowInsertChar(erow *row, int at, int c) {
row->size++;
row->chars[at] = c;
editorUpdateRow(row);
E.dirty++;
}
@ -298,6 +302,7 @@ void editorOpen(char *filename) {
}
free(line);
fclose(fp);
E.dirty = 0;
}
void editorSave() {
@ -312,6 +317,7 @@ void editorSave() {
if (write(fd, buf, len) == len) {
close(fd);
free(buf);
E.dirty = 0;
editorSetStatusMessage("%d bytes written to disk", len);
return;
}
@ -400,8 +406,9 @@ void editorDrawRows(struct abuf *ab) {
void editorDrawStatusBar(struct abuf *ab) {
abAppend(ab, "\x1b[7m", 4);
char status[80], rstatus[80];
int len = snprintf(status, sizeof(status), "%.20s - %d lines",
E.filename ? E.filename : "[No Name]", E.numrows);
int len = snprintf(status, sizeof(status), "%.20s - %d lines %s",
E.filename ? E.filename : "[No Name]", E.numrows,
E.dirty ? "(modified)" : "");
int rlen = snprintf(rstatus, sizeof(rstatus), "%d/%d",
E.cy + 1, E.numrows);
if (len > E.screencols) len = E.screencols;
@ -501,6 +508,8 @@ void editorMoveCursor(int key) {
void editorProcessKeypress() {
static int quit_times = KILO_QUIT_TIMES;
int c = editorReadKey(); // Blocking!
switch (c) {
@ -509,6 +518,12 @@ void editorProcessKeypress() {
break;
case CTRL_KEY('q'):
if (E.dirty && quit_times > 0) {
editorSetStatusMessage("WARNING!!! File has unsaved changes. "
"Press CTRL-Q %d more times to quit.", quit_times);
quit_times--;
return;
}
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
@ -563,6 +578,8 @@ void editorProcessKeypress() {
editorInsertChar(c);
break;
}
quit_times = KILO_QUIT_TIMES;
}
/*** init ***/
@ -575,6 +592,7 @@ void initEditor() {
E.coloff = 0;
E.numrows = 0;
E.row = NULL;
E.dirty = 0;
E.filename = NULL;
E.statusmsg[0] = '\0';
E.statusmsg_time = 0;