Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to use macros in vim for batch operations

Shulou Source: shulou.com Published: 2022-06-03 03:47:48 09月18日 Update

Brief introduction

The essence of macros in vim is to store a set of vim instructions in a register and then call the instructions in the register.

Use the macro command to repeat the commands you have recorded.

Press in command mode

QQ + a series of commands + Q

Refers to a register in a user-defined amurz

Q + start recording command

Q complete the record and exit the record

Example: qa

Vim command

Q

This macro only records the vim command to register a. You can execute this macro with the command:

@ a

You can also add the number of executions:

10 executes 10 times

After you have executed @ an once, you can repeat @ a with @ @.

Use macros

The use of macros is divided into recording and playback. Vim uses the Q key to start recording, which is also a Q as the end button of the macro.

Use Q {register} to select the register you want to hold, and the function of this register is to save the recorded commands in it.

Use @ {register} to play back the collection of commands in the register. If you want to play the macro multiple times, you can use the number + @ {register}, such as 10rooma.

Actual combat

So much for the introduction of Acer, now let's complete the requirements we just said at the beginning. First of all, complete the function of batch commenting code. Here, instead of macros, we use block selection and command-line mode to accomplish the requirement. For the second requirement, we use macros to accomplish it.

Here is a piece of code:

We chose to comment out the free method.

First we come to line 70 and press 70g to line 70 in normal mode. Press V to enter block selection mode, and then move the cursor to select all the lines you want to comment. Input: enter command line mode, type normal 0i _ enter, and then press the command key.

Next, let's use macros to complete another requirement-batch indentation.

You can see that there are a lot of spaces on the left. Now let's eliminate these useless spaces. First of all, come to the first line, press qa to start recording the macro; press 0w, come to the first non-space string, press I, and then backspace until all the spaces are deleted; then press the Q key to end the recording, and then the macro is done, and then you can play the macro to the remaining lines. Enter block selection mode, select all the remaining lines, and press: normal @ a.

These are the details of using VIM macros (macro) to complete batch operations, please pay attention to other related articles!

Tags: Commands registers selections patterns that is spaces requirements comments code functions instructions input normal next one line no cursor content and at the same time characters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Tech Info Apple MariaDB Xiaomi