Using yasnippet
You did not mention what programming language major mode you are working in. So let me provide an example for c-mode
.
First time setup
Step 1: Install yasnippet
You will need to install the yasnippet
package (also available from Melpa) to implement the below solution.
Check out this wonderful introduction to yasnippet especially if you are a first time user.
Step 2: Create a snippet for if
condition for your major mode.
By default yasnippet
picks up snippets saved in the ~/.emacs.d/snippets/
directory. Within that directory, you would have a directory for each of the major modes for which you plan to use yasnippet
. So that directory would be c-mode/
in this case. Save the below code snippet as ~/.emacs.d/snippets/c-mode/if
file.
# -*- mode: snippet -*-
# name: if
# key: if
# expand-env: ((yas-indent-line 'auto) (yas-also-auto-indent-first-line t) (yas-wrap-around-region t))
# --
if (${1:some_condition}) {
$0
}
Take note of the (yas-wrap-around-region t)
portion in the expand-env:
line above. That is what will allow you to select a region and wrap it with the snippet expansion. The other options in that line are for auto-indentation convenience.
Step 3: Load your new snippet using M-x yas-reload-all
.
Using the snippet once everything is set
Step 1: Select the code which you want to wrap with if
condition.
Suppose this is the code:
foo();
bar();
Step 2: Insert your snippet
M-x yas-insert-snippet
- Select the
if
snippet
Result
if (some_condition) {
foo();
bar();
}