An improved (I think) version of the diff by op@, making the keywords
string+length pairs as the length is known at compile time, and also removing
an unnecessary "clever" hack that indented once for every brace on the line,
which shouldn't happen in practice with well-formatted code.
Index: cmode.c
===================================================================
RCS file: /cvs/src/usr.bin/mg/cmode.c,v
diff -u -p -r1.23 cmode.c
--- cmode.c 21 May 2024 05:00:48 -0000 1.23
+++ cmode.c 9 Nov 2026 23:11:13 -0000
@@ -14,6 +14,7 @@
#include <ctype.h>
#include <signal.h>
#include <stdio.h>
+#include <string.h>
#include "def.h"
#include "funmap.h"
@@ -85,6 +86,21 @@ static struct KEYMAPE (3) cmodemap = {
}
};
+/* grammar */
+
+#define KEYWORD(kw) { kw, sizeof(kw) - 1 }
+
+static const struct {
+ const char *str;
+ size_t len;
+} keywords[] = {
+ KEYWORD("do"),
+ KEYWORD("else"),
+ KEYWORD("if"),
+ KEYWORD("for"),
+ KEYWORD("while"),
+};
+
/* Function, Mode hooks */
void
@@ -237,6 +253,8 @@ getindent(const struct line *lp, int *cu
int astp = FALSE; /* Asterisk? */
int cpos = -1; /* comment position */
int cppp = FALSE; /* Preprocessor command? */
+ int keywordp = FALSE; /* looking at a keyword? */
+ int i;
*curi = 0;
@@ -250,6 +268,17 @@ getindent(const struct line *lp, int *cu
nicol++;
}
+ /* Does it starts with a keyword that accepts no braces? */
+ for (i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) {
+ size_t t = keywords[i].len;
+ if (t > llength(lp) - lo)
+ t = llength(lp) - lo;
+ if (strncmp(lp->l_text + lo, keywords[i].str, t) == 0) {
+ keywordp = TRUE;
+ break;
+ }
+ }
+
/* If last line was blank, choose 0 */
if (lo == llength(lp))
nicol = 0;
@@ -324,10 +353,18 @@ getindent(const struct line *lp, int *cu
if (colonp) {
*curi += cc_colon_indent;
newind -= cc_colon_indent;
+ } else if (keywordp && obrace == 0) {
+ /*
+ * otherwise, if the line starts with a keyword but
+ * no brace, indent anyway
+ */
+ newind += cc_basic_indent;
}
- *curi -= (cbrace) * cc_basic_indent;
- newind += obrace * cc_basic_indent;
+ if (cbrace)
+ *curi -= cc_basic_indent;
+ if (obrace)
+ newind += cc_basic_indent;
if (nparen < 0)
newind -= cc_cont_indent;
I think there are unfortunately more issues with c-mode that would require
changing a lot of the code -- for instance, getting the indentation of lines
following an unbraced statement correct would require (i think) looking back
more than one line, which the current code isn't doing (correct me if that's
not the case). Also, the indentation heuristics often "get confused" with
syntax like structure initializers... Worst of all, it's impossible to input
a tab in the middle of a line without using M-x insert, which makes it hard
to write KNF-style prototypes or structures, both of which use tabs.
C-mode seems very hacky in general and the annoyances outweigh the benefits,
but I'm going to try to improve some of the issues if I find the time and
send patches eventually.