Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generate values for #define using vi[m]

Tags:

c++

c

vim

vi

macros

As of now, I have the following in a .h file which has the following:

#define ONE 
#define TWO
#define THREE
#define FOUR
..
.
#define FIFTY

Using vi[m], how can we generate the replacement text for the macros which should be as follows:

#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
..
.
#define FIFTY 50

Problem statement: Given lower-limit (1), upper-limit (50) and step (i.e. increment by 1 or 2 or 3, etc at a time) - what is the vi command to automatically generate values in the above mentioned macros?

UPDATE: I have no option of using enum.

like image 474
Sangeeth Saravanaraj Avatar asked Feb 17 '23 16:02

Sangeeth Saravanaraj


2 Answers

Go ahead and put a "1" after the #define ONE (where it should be at the final state). Go to the beginning of that line (with the cursor over the #) and press the following keys (where C-a means "ctrl+a"):

q q # record macro q
3 w h y $ j $ p C-a ^ q # end macro q
4 8 @ q # repeat macro 48x

Now the explanation:

  • qq = record a macro called "q"
  • 3w = move three words to the right
  • h = move one character left (over the space before the number)
  • y$ = yank until the end of the line
  • j = move down one line
  • $ = go to the end of the line
  • p = paste
  • C-a = increment the number under the cursor
  • ^ = go to the beginning of the line
  • q = stop recording macro
  • 48@q = run the macro 48 times

Let me know if you didn't understand, or if I understood it wrongly. It works correctly in my PC. If you want to increment by more then one at a time, simply put that multiplier in front of C-a (e.g. 3C-a)

like image 143
Daniel Fleischman Avatar answered Feb 20 '23 05:02

Daniel Fleischman


Line-select (C-V) all the lines and type

:r !awk '{print $0, NR}'
like image 32
Michael Wild Avatar answered Feb 20 '23 06:02

Michael Wild