[Tex/LaTex] Indentation in AUCTEX and algorithmic package

algorithmsauctexemacsindentation

When working with EMACS+AUCTEX I encountered the problem of proper indentation when using the algorithmic package.

In this MWE:

\documentclass[12pt]{article}
\usepackage{algorithmic}
\begin{document}
\begin{algorithmic}
  \IF {list.first $\neq x_{min}$} 
  \STATE bla 
  \STATE bla 2
  \ENDIF
\end{algorithmic}
\end{document}

I have a correct indentation, but hitting C-c C-q C-e in the algorithm's environment, produces:

\begin{algorithmic}
  \IF {list.first $\neq x_{min}$} \STATE bla \STATE bla 2
  \ENDIF
\end{algorithmic}

When trying to add a nested if, I fail to obtain good indentation completely.

Does anyone know the problem? Possible solutions?

Best Answer

Emacs is really smart about indentation. Unfortunately, you have to be even smarter to get it to do something new.

The easiest thing to do in this case is to customize the variable LaTeX-paragraph-commands. By default, this is empty. If you add IF and STATE, then C-c C-q C-e should respect your wishes and not jumble everything up together.

To do this, call M-x customize-variable LaTeX-paragraph-commands, click the INS button and add IF in the string box, click INS again and add STATE to a second string box. The click apply and save.

Getting proper indentation of nested IF statements is going to be trickier. One approach is to customize the variables LaTeX-begin-regexp and LaTeX-end-regexp. The first defaults to begin\b, and the second to end\b. If you extend them to begin\b\|IF\b and end\b\|ENDIF\b respectively, Auctex will indent your IF blocks how you like.

To do this, call M-x customize-variable LaTeX-begin-regexp and change begin\b to begin\b\|IF\b, and then click apply and save. Do the same for LaTeX-end-regexp, adding the \|ENDIF\b bit.

However, if you don't close your IF blocks with an ENDIF, then the indentation doesn't return to normal when you leave your algorithmic environment. To get Auctex to properly handle un-ended IF blocks, you need to cook up a custom indentation function. I don't know how to do that yet, but may return when I do.