简体   繁体   中英

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?

Mx 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

You can use Cx 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' .

Here's a quick fix. With a bit of work you could make this general - ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM