问题
I'm using emacs with cdlatex-mode to edit LaTeX files. I would like to know how to insert a LaTeX environment around a block of text that is already written so that the \begin{}
goes before the selected text and the \end{}
goes after the selected text. I've tried to use cdlatex-environment function but doing so erases the selected text.
回答1:
AUCTeX
If you use auctex:
- Mark the block of text you want to enclose in an environment.
- Press C-c C-e.
- Enter an environment type of your choice (you can only type some characters and use tab completion) and press Enter.
See the manual for details.
Note that there is a similar method to enclose marked text in macros. Do as 1–3 but instead press C-c C-e or C-c Enter instead. See the manual for details.
YASnippet
If you use YASnippet you can create a snippet with similar behavior as above. For example you can use the following (you have replace "keybinding" with a proper keybinding):
# -*- mode: snippet -*-
# name: LaTeX environment
# key: "keybinding"
# --
\begin{$1}
`yas/selected-text`$0
\end{$1}
If you want a snippet for macros too you can use something like the following:
# -*- mode: snippet -*-
# name: LaTeX macro
# key: "keybinding"
# --
\$1{`yas/selected-text`$0}
Elisp
Even if I recommend the above approaches there might be situations where you want instead to use some simple elisp function. The following is just something rough which has far less functionality than the above approaches:
(defun ltx-environment (start end env)
"Insert LaTeX environment."
(interactive "r\nsEnvironment type: ")
(save-excursion
(if (region-active-p)
(progn
(goto-char end)
(newline)
(insert "\\end{" env "}")
(goto-char start)
(insert "\\begin{" env "}") (newline))
(insert "\\begin{" env "}") (newline) (newline)
(insert "\\end{" env "} "))))
And for macros if you want that too:
(defun ltx-macro (start end env)
"Insert LaTeX macro."
(interactive "r\nsMacro: ")
(save-excursion
(if (region-active-p)
(progn
(goto-char end) (insert "}")
(goto-char start) (insert "\\" env "{"))
(insert "\\" env "{}"))))
To use them put them in your .emacs and do M-x ltx-environment
or ltx-macro
respectively.
回答2:
Following the suggestion in an answer here by Tikhon Jelvis, I had a look at the latex mode documentation (C-h m) and found mention of the function
latex-insert-block
which seems to do exactly what you want.
The shortcut key is C-c C-t (whenever you are in latex mode).
来源:https://stackoverflow.com/questions/9082999/how-to-insert-a-latex-environment-around-a-block-of-text-in-emacs