Skip to content

Commit bf852b8

Browse files
committed
[javascript mode] Improve indentation of hanging else clauses
Closes #2429
1 parent 9ba268b commit bf852b8

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

mode/javascript/javascript.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
314314
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
315315
if (type == "{") return cont(pushlex("}"), block, poplex);
316316
if (type == ";") return cont();
317-
if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse);
317+
if (type == "if") {
318+
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
319+
cx.state.cc.pop()();
320+
return cont(pushlex("form"), expression, statement, poplex, maybeelse);
321+
}
318322
if (type == "function") return cont(functiondef);
319323
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
320324
if (type == "variable") return cont(pushlex("stat"), maybelabel);
@@ -482,7 +486,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
482486
if (type == ",") return cont(vardef);
483487
}
484488
function maybeelse(type, value) {
485-
if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex);
489+
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
486490
}
487491
function forspec(type) {
488492
if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
@@ -595,7 +599,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
595599
if (state.tokenize != tokenBase) return 0;
596600
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
597601
// Kludge to prevent 'maybelse' from blocking lexical scope pops
598-
for (var i = state.cc.length - 1; i >= 0; --i) {
602+
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
599603
var c = state.cc[i];
600604
if (c == poplex) lexical = lexical.prev;
601605
else if (c != maybeelse) break;

mode/javascript/test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,22 @@
104104
" [keyword debugger];",
105105
"}");
106106

107+
MT("indent_else",
108+
"[keyword for] (;;)",
109+
" [keyword if] ([variable foo])",
110+
" [keyword if] ([variable bar])",
111+
" [number 1];",
112+
" [keyword else]",
113+
" [number 2];",
114+
" [keyword else]",
115+
" [number 3];");
116+
117+
MT("indent_below_if",
118+
"[keyword for] (;;)",
119+
" [keyword if] ([variable foo])",
120+
" [number 1];",
121+
"[number 2];");
122+
107123
MT("multilinestring",
108124
"[keyword var] [variable x] [operator =] [string 'foo\\]",
109125
"[string bar'];");

0 commit comments

Comments
 (0)