7
votes

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?

3
Both u-punkt and Simon provide answers that work. Is there anyway to speed up this process e.g. a small function in my .emacs that can start c-mode, indent, and switch back to LaTeX mode?jarvisschultz
I think my answer will do what you want.Tyler
In case you weren't aware, have you looked at the latex Listings package? I believe you can just input the source code so no need to copy and paste.TreyA
I have used listings package, as well as minted (which I like better), they do not do what I want. They format code during the latex compilation, I am talking about formatting a raw text ".tex" file.jarvisschultz
Understood, what I was suggesting was to move the verbatim blocks out of the .tex file and put the source code in a .c file. Then, when you view/edit the .c in emacs, it will do the proper c formatting. In the .tex file, you would include the source via \lstinputlisting{source_filename.c} where your verbatim blocks are now.TreyA

3 Answers

4
votes

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
4
votes

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'.

3
votes

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.