# Auto-Indenting \if statements with AUCTeX

The current AUCTeX behaviour for primitive tex code involving if-like statements is to indent the conditional statement at the same level as the surrounding condition. I.e. code such as

\if@sometoggle%
\dosomething%
\else%
\doanotherthing%
\fi%


appears as a big block of text. I would like to make AUCTeX indent the snippet as follows:

\if@sometoggle%
\dosomething%
\else%
\doanotherthing%
\fi%


Is this possible?

It's possible:

(setq LaTeX-begin-regexp "\$$?:begin\\|if@\$$\\b")
(setq LaTeX-end-regexp "\$$?:end\\|else\\|fi\$$\\b")
(defun LaTeX-indent-level-count ()
"Count indentation change caused by all \\left, \\right, \\begin, and
\\end commands in the current line."
(save-excursion
(save-restriction
(let ((count 0))
(narrow-to-region (point)
(save-excursion
(re-search-forward
(concat "[^" TeX-esc "]"
"\$$" LaTeX-indent-comment-start-regexp "\$$\\|\n\\|\\'"))
(backward-char)
(point)))
(while (search-forward TeX-esc nil t)
(cond
((looking-at "left\\b")
(setq count (+ count LaTeX-left-right-indent-level)))
((looking-at "right\\b")
(setq count (- count LaTeX-left-right-indent-level)))
((looking-at LaTeX-begin-regexp)
(setq count (+ count LaTeX-indent-level)))
((looking-at "else\\b"))
((looking-at LaTeX-end-regexp)
(setq count (- count LaTeX-indent-level)))
((looking-at (regexp-quote TeX-esc))
(forward-char 1))))
count))))


Note that I had to re-define LaTeX-indent-level-count. The diff is simply one cond branch:

((looking-at "else\\b"))

• Works like a charm! – elemakil Apr 15 '15 at 10:32
• Having the same problem as the OP, I copied your code and it worked, but not fully satisfactory. It indents only till the next \else. The position of the \else is correct, but the following code (\doanotherthin, see question) is still in the first column, instead of column 3. I changed your first code line, to incorporate also the \ifx-command and thought, adding the else command would help, but I failed (at least with again indenting after \else). So here is my partially working code: (setq LaTeX-begin-regexp "\$$?:begin\\|if\\|ifx\\|else\$$\\b") Any ideas? – Jan Apr 8 '18 at 15:01