3 var _br = require('rocambole-linebreak');
4 var _tk = require('rocambole-token');
5 var _ws = require('rocambole-whitespace');
6 var _limit = require('../limit');
9 exports.format = function IfStatement(node) {
11 var startBody = node.consequent.startToken;
12 var endBody = node.consequent.endToken;
14 var conditionalStart = _tk.findPrev(node.test.startToken, '(');
15 var conditionalEnd = _tk.findNext(node.test.endToken, ')');
17 _ws.limit(conditionalStart, 'IfStatementConditionalOpening');
18 _ws.limit(conditionalEnd, 'IfStatementConditionalClosing');
20 var alt = node.alternate;
22 var elseKeyword = _tk.findPrev(alt.startToken, 'else');
24 if (alt.type === 'IfStatement') {
26 _br.limitBefore(alt.startToken, 0);
27 _ws.limitBefore(alt.startToken, 1);
29 if (alt.consequent.type === 'BlockStatement') {
30 _br.limitBefore(alt.consequent.startToken, 'ElseIfStatementOpeningBrace');
31 _br.limitBefore(alt.consequent.endToken, 'ElseIfStatementClosingBrace');
34 _br.limitBefore(elseKeyword, 'ElseIfStatement');
35 if (! alt.alternate) {
36 // we only limit the line breaks after the ElseIfStatement if it is not
37 // followed by an ElseStatement, otherwise it would add line breaks
39 _br.limitAfter(alt.consequent.endToken, 'ElseIfStatement');
42 } else if (alt.type === 'BlockStatement') {
45 _limit.around(alt.startToken, 'ElseStatementOpeningBrace');
47 _br.limitBefore(elseKeyword, 'ElseStatement');
48 _br.limitAfter(alt.endToken, 'ElseStatement');
50 _ws.limitBefore(elseKeyword, 1);
52 _limit.around(alt.endToken, 'ElseStatementClosingBrace');
54 // ElseStatement without curly braces
55 _ws.limitAfter(elseKeyword, 1);
59 // only handle braces if block statement
60 if (node.consequent.type === 'BlockStatement') {
61 _limit.around(startBody, 'IfStatementOpeningBrace');
63 _br.limit(endBody, 'IfStatementClosingBrace');
65 _br.limitBefore(endBody, 'IfStatementClosingBrace');
67 _ws.limit(endBody, 'IfStatementClosingBrace');
73 exports.getIndentEdges = function(node, opts) {
77 var consequent = node.consequent;
78 var alt = node.alternate;
80 // test (IfStatementConditional)
82 level: opts.IfStatementConditional,
83 startToken: _tk.findNext(node.startToken, '('),
84 endToken: _tk.findPrev(consequent.startToken, ')'),
87 function isExecutable(token) {
88 return _tk.isNotEmpty(token) && !_tk.isComment(token);
94 consequent.type === 'BlockStatement' ?
95 consequent.startToken :
98 // we have some special rules for comments just before the `else` statement
99 // because of jQuery style guide. maybe in the future we will add
100 // a setting to toggle this behavior (if someone asks for it)
102 alt && _tk.isComment(_tk.findPrevNonEmpty(consequent.endToken)) ?
103 _tk.findPrev(consequent.endToken, isExecutable).next :
109 if (alt && alt.type !== 'IfStatement') {
110 // it the alternate is IfStatement it will already take care of indentation
113 alt.type === 'BlockStatement' ?
115 _tk.findPrevNonEmpty(alt.startToken).next
117 endToken: alt.endToken