Marc A.
Marc A.

Reputation: 148

Surrounding multiple selected lines with #ifdef

I'm trying to write a macro that will allow me to surround currently highlighted lines of text with an #ifdef. Ideally with the cursor placed after the #ifdef to be ready to enter the macro name. I'm able to record to create a macro, but I'm only able to do it for one line of code.

Before:

    bool first_selected_line = false;
    int second_selected_line = 0;

After:

#ifdef // if possible, cursor placed here in insert mode
    bool first_selected_line = false;
    int second_selected_line = 0;
#else
    bool first_selected_line = false;
    int second_selected_line = 0;
#endif

Any ideas?

Upvotes: 1

Views: 391

Answers (2)

Daan Bakker
Daan Bakker

Reputation: 6332

You could do something along the lines of:

qjc#ifdef<esc>magpO#else<esc>gpO#endif<esc>`aq

Basically:

  • Start recording qj
  • Delete what you selected and go into insertmode c
  • Type your construct, pasting your code back as necessary
  • You put a mark (ma) just after typing #ifdef and jump back to it at the end
  • Repeat the macro with @j

Hope this example helps!

Upvotes: 2

Conner
Conner

Reputation: 31040

I would probably use snipmate or some other plugin to accomplish this task. There are couple ways to go about it manually though. Here's my solution for a macro:

Visually select the text then...

qqc#ifdef 
<C-r><C-o>"
#else
<C-r><C-o>"
#endif<esc>'[A<C-o>q

You also don't have to visually select the text at all if you don't want to. Use the same macro but start with qqcj instead.

Upvotes: 1

Related Questions