How to insert LaTeX environment around a block of text in emacs?

I am 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 \begin{} goes before the selected text, and \end{} after the selected text. I tried using the cdlatex-environment function, but it erases the selected text.

+7
source share
2 answers

Auctex

If you are using :

  • Check the box of text you want to wrap on Wednesday.
  • Click Cc Ce .
  • Enter the type of environment of your choice (you can enter only some characters and use the tab) and press Enter .

See the manual for more details.

Note that there is a similar method for adding tagged text to macros. Do as 1-3, but instead press Cc Ce or Cc Enter . See the manual for more details.

Yasnippet

If you use YASnippet , you can create a snippet with the same behavior as above. For example, you can use the following (you have the replacement "keybinding" using proper keybinding):

 # -*- mode: snippet -*- # name: LaTeX environment # key: "keybinding" # -- \begin{$1} `yas/selected-text`$0 \end{$1} 

If you need a macro fragment, 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 may be situations when you want to use some simple elisp function. The following is something rude, which has much 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 this 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 execute Mx ltx-environment or ltx-macro respectively.

+6
source

Following the sentence in <here by Tikhon Elvis, I looked at the latex mode documentation (Ch m) and found a mention of the function

 latex-insert-block 

which seems to be doing exactly what you want.

The shortcut key is Cc Ct (whenever you are in latex mode).

0
source

All Articles