kilo

Kilo: minimal text editor written in C
git clone git://git.dimitrijedobrota.com/kilo.git
Log | Files | Refs

commit c5abe8f4ebfc671d324e3e38dcf2f9352fda9ef8
parent 7b402b17b4b1e56094ab2acd4f950d4c9296d3ae
Author: Dimitrije Dobrota <mail@dimitrijedobrota.com>
Date:   Sun,  9 Apr 2023 20:32:17 +0200

Indent new line as the previous one

Diffstat:
Mkilo.c | 33+++++++++++++++++++++++----------
1 file changed, 23 insertions(+), 10 deletions(-)

diff --git a/kilo.c b/kilo.c @@ -520,6 +520,16 @@ void editorSelectSyntaxHighlight() { /*** row operations ***/ +int editorRowIndent(erow *row) { + char *p = row->chars; + while (isspace(*p++)) + ; + return p - row->chars - 1; + + // on blank line return 0 + // return *p ? p - row->chars - 1 : 0; +} + int editorRowCxToRx(erow *row, int cx) { int rx = 0; for (int j = 0; j < cx; j++) { @@ -563,7 +573,7 @@ void editorUpdateRow(erow *row) { editorUpdateSyntax(row); } -void editorInsertRow(int at, char *s, size_t len) { +void editorInsertRow(int at, char *s, size_t len, int indent) { if (at < 0 || at > E.numrows) return; E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); @@ -572,10 +582,12 @@ void editorInsertRow(int at, char *s, size_t len) { E.row[at].idx = at; - E.row[at].size = len; - E.row[at].chars = malloc(len + 1); - memcpy(E.row[at].chars, s, len); - E.row[at].chars[len] = '\0'; + int tlen = indent + len; + E.row[at].size = tlen; + E.row[at].chars = malloc(tlen + 1); + memcpy(E.row[at].chars, E.row[at - 1].chars, indent); + memcpy(E.row[at].chars + indent, s, len); + E.row[at].chars[tlen] = '\0'; E.row[at].rsize = 0; E.row[at].render = NULL; @@ -636,7 +648,7 @@ void editorRowDelChar(erow *row, int at) { /*** editor operations ***/ void editorInsertChar(int c) { - if (E.cy == E.numrows) { editorInsertRow(E.numrows, "", 0); } + if (E.cy == E.numrows) { editorInsertRow(E.numrows, "", 0, 0); } if (KILO_TAP_SOFT && c == '\t') { for (int i = 0; i < KILO_TAB_STOP; i++) @@ -649,17 +661,18 @@ void editorInsertChar(int c) { void editorInsertNewline() { if (E.cx == 0) { - editorInsertRow(E.cy, "", 0); + editorInsertRow(E.cy, "", 0, 0); } else { + int indent = editorRowIndent(&E.row[E.cy]); erow *row = &E.row[E.cy]; - editorInsertRow(E.cy + 1, &row->chars[E.cx], row->size - E.cx); + editorInsertRow(E.cy + 1, &row->chars[E.cx], row->size - E.cx, indent); row = &E.row[E.cy]; // reassign in case realloc changes it row->size = E.cx; row->chars[row->size] = '\0'; editorUpdateRow(row); + E.cx = indent; } E.cy++; - E.cx = 0; } void editorDelChar() { @@ -712,7 +725,7 @@ void editorOpen(char *filename) { (line[linelen - 1] == '\n' || line[linelen - 1] == '\r')) linelen--; - editorInsertRow(E.numrows, line, linelen); + editorInsertRow(E.numrows, line, linelen, 0); } free(line); fclose(fp);