3

In various programming modes, assuming I have a few lines of code like this :

foo()
bar()

And I want to turn it into a block (say, and if of some sort)

if (something) {
  foo()
  bar()
}

Is there, in general, a more clever way than :

  • selecting the region
  • yaking it
  • typing the if... line
  • pasting the region

I'm probably just missing the name of something ("wrapping" ?)

phtrivier
  • 135
  • 5
  • With the built-in electric-pair-mode, if you type `{` while a region is selected, it will put a pair of `{}` around the selected region. It might not adjust the indentation appropriately itself. – Kirill Sep 23 '15 at 22:26

2 Answers2

2

I usually use smartparens for this. First, write in your if statement, leaving the point where the pipe | is:

if (condition) {|}
foo();
bar();

Then call the function sp-slurp-hybrid-sexp twice:

if (condition) {
    foo();
    bar();
}

See the smartparens wiki page for more info on "hybrid s-exps".

nanny
  • 5,704
  • 18
  • 38
2

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();
 }
Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179