Search code examples
emacslatex

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


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.


Solution

  • AUCTeX

    If you use :

    1. Mark the block of text you want to enclose in an environment.
    2. Press C-c C-e.
    3. 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.