Skip to content

Commit

Permalink
Indent and unindent based on the last char of the previous line
Browse files Browse the repository at this point in the history
Two new field where added to the editorSyntax struct
indent_chars and unindent_chars helps to identify when a line
should be indented/unindented.

If the previous line has any of the indent_chars as its last
non whitespace character, the next line will be indented.

If the current line has any of the unindent_chars as its first non
whitepace character, the line will be unindented.
  • Loading branch information
sney2002 committed Jun 24, 2020
1 parent 3cb2ec2 commit a42e308
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions kilo.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ struct editorSyntax {
char *singleline_comment_start;
char *multiline_comment_start;
char *multiline_comment_end;
char *indent_chars;
char *unindent_chars;
int flags;
};

Expand Down Expand Up @@ -125,6 +127,7 @@ struct editorSyntax HLDB[] = {
C_HL_extensions,
C_HL_keywords,
"//", "/*", "*/",
"{[", "}]",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
};
Expand Down Expand Up @@ -702,13 +705,31 @@ void editorInsertChar(int c) {
}

void editorAutoIndent(int prev) {
if (prev <= 0) return;
if (prev < 0) return;
char *prev_row = E.row[prev].chars;
char last_char = -1;

while (IS_TAB(*prev_row) || *prev_row == ' ') {
editorInsertChar(*prev_row);
prev_row++;
}

while (*prev_row) {
if (!IS_TAB(*prev_row) && *prev_row != ' ') {
last_char = *prev_row;
}
prev_row++;
}

if (strchr(E.syntax->indent_chars, last_char) != NULL) {
if (E.expandtab) {
for (int i = 0; i < KILO_TAB_STOP; i++) {
editorInsertChar(' ');
}
} else {
editorInsertChar('\t');
}
}
}

void editorInsertNewline() {
Expand Down Expand Up @@ -1360,6 +1381,24 @@ void editorProcessInsertModeKeypress() {

default:
if (!IS_TAB(c) || E.expandtab == 0) {
if (strchr(E.syntax->unindent_chars, c) == NULL) {
editorInsertChar(c);
return;
}


for (int i = E.cx - 1; i >= 0; i--) {
char p = E.row[E.cy].chars[i];
if (!IS_TAB(p) && p != ' ') {
editorInsertChar(c);
return;
}
}

for (int i = 0; i < KILO_TAB_STOP; i++) {
if (E.cx > 0) editorDelChar();
}

editorInsertChar(c);
return;
}
Expand Down Expand Up @@ -1483,7 +1522,7 @@ void editorProcessNormalModeKeypress() {
editorMoveCursor(HOME_KEY);
editorInsertNewline();
editorMoveCursor(ARROW_UP);
editorAutoIndent(E.cy + 1);
editorAutoIndent(E.cy - 1);
break;
}

Expand Down

0 comments on commit a42e308

Please sign in to comment.