Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent a region of C code in LaTeX mode emacs

My problem is that I am writing a LaTeX document in emacs that has a lot of C code in it. I am using both the \minted and the \verbatim environments in various places. When I compile the LaTeX (using pdflatex), the resulting pdf looks fine. In the raw LaTeX code, I would like to be able to auto-indent using the rules of the C-major mode.

For example, I want to be able to mark the following region

\begin{verbatim} 

void main(void)
{
printf("Hello World \n\r");
}

\end{verbatim}

And have emacs auto-format it to look like

\begin{verbatim}

void main(void)
{
    printf("Hello World \n\r");
}

\end{verbatim}   

In other words, I want to be able to run indent-region on the part that is actually C code using the rules from C mode, even though I am in LaTeX mode.

Does anyone know if this is possible?

like image 297
jarvisschultz Avatar asked Jan 11 '12 15:01

jarvisschultz


3 Answers

M-x indent-region indents only the region, not the full buffer, so:

  1. Turn on C mode
  2. Indent your region
  3. Turn back on LaTeX mode
like image 138
Simon Avatar answered Nov 11 '22 10:11

Simon


You can use C-x 4 c to clone your current buffer to an indirect buffer. Put that indirect buffer in to c-mode and do your indenting there. For further information on indirect buffers see the Emacs info manual, node 'Indirect Buffers'.

like image 32
u-punkt Avatar answered Nov 11 '22 09:11

u-punkt


Here's a quick fix. With a bit of work you could make this general - i.e., check for the current major-mode, and switch back to that mode after you're done. As is, it switches to c-mode, indents, then switches to LaTeX-mode (AucTex), which solves the immediate problem:

(defun indent-region-as-c (beg end)
  "Switch to c-mode, indent the region, then switch back to LaTeX mode."
  (interactive "r")
  (save-restriction
    (narrow-to-region beg end)
    (c-mode)
    (indent-region (point-min) (point-max)))
    (LaTeX-mode))

Bind that to your favourite key and you should be all set.

like image 26
Tyler Avatar answered Nov 11 '22 11:11

Tyler