Indented C code area in LaTeX emacs mode

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

For example, I want to mark the following area

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

And emacs automatically formats 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 the indentation region into the part, which is actually C code, using the rules from C mode, even if I enter LaTeX mode.

Does anyone know if this is possible?

+7
source share
3 answers

Here is a quick fix. With a little work you can do this in general - that is, check the current main mode and return to this mode after you are done. As in the case, it switches to c-mode, indents, and 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 this to your favorite key and everything should be set.

+3
source

Mx indent-region only allocates a region, not a full buffer, so:

  • Turn on mode C
  • Indentation in your area
  • Return to LaTeX mode
+4
source

You can use Cx 4 c to clone the current buffer into an indirect buffer. Put this indirect buffer in c-mode and indent. For more information on indirect buffers, see the Emacs Reference Guide, node โ€œIndirect Buffersโ€ .

+4
source

All Articles