4coder » Forums » Can we talk about macros?
nakst
59 posts / 1 project
....
#16846 Can we talk about macros?
3 weeks ago


If I have the code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    init_a_thingy(thingy_ctx, "Foo", 0, foo_func);
    init_a_thingy(thingy_ctx, "Bar", 0, bar_func);
    init_a_thingy(thingy_ctx, "Fiz", 1, foo_func);
    init_a_thingy(thingy_ctx, "Faz", 2, faz_func);
    init_a_thingy(thingy_ctx, "Bat", 1, bar_func);
    init_a_thingy(thingy_ctx, "Foo Big", 3, foo_func);
    init_a_thingy(thingy_ctx, "Bar Big", 3, bar_func);
    init_a_thingy(thingy_ctx, "Fiz Gigantic", 100, foo_func);
    init_a_thingy(thingy_ctx, "Faz Tiny", -1, faz_func);
    init_a_thingy(thingy_ctx, "Bat Goofy", 10, foo_func);


And if I want to turn it into this code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    {"Foo", 0, foo_func,},
    {"Bar", 0, bar_func,},
    {"Fiz", 1, foo_func,},
    {"Faz", 2, faz_func,},
    {"Bat", 1, bar_func,},
    {"Foo Big", 3, foo_func,},
    {"Bar Big", 3, bar_func,},
    {"Fiz Gigantic", 100, foo_func,},
    {"Faz Tiny", -1, faz_func,},
    {"Bat Goofy", 10, foo_func,},


Then I have a fairly basic use case for a macro system.


Vim users would disagree.

I'd start by making a block selection of all the "init_a_thingy(thingy_ctx, "s.
1
<C-V>9jt"

'<C-V>' is Ctrl+V, and starts the block selection. '9j' moves down 9 lines. 't"' moves to the character before the first '"'.

Then I'd replace each with '{'.
1
c{<ESC>

'c' deletes the selected text and enters insert mode. '{' inserts the character. '<ESC>' is escape, which exits insert mode and repeats the operation for all previous selected lines.

Then to change the ');' at the end of each line to ',},'
I'd modify the first line as follows:
1
A<BS><BS>,},<ESC>

'A' moves the caret to the end of the line and enters insert mode. '<BS><BS>' backspaces 2 characters, ',},' inserts the text. '<ESC>' exits insert mode.

I'd then repeat this for each line:
1
j.j.j.j.j.j.j.j.

'j' moves down a line. '.' repeats the whole last operation - 'A<BS><BS>,},<ESC>' (the operation ends when we exit insert mode).
This is a very powerful feature of vim, to be able to replay the last modification operation you did without having to record a macro.

Only if there were more lines would I think about creating a macro.
1
qqvt"c{<END><BS><BS>,},<ESC>j0q

'qq' records a keyboard macro to register 'q'. 'vt"c{' replaces the start text with a '{'. '<END><BS><BS>,},<ESC>' edits the edit of the line and then exits insert mode. 'j0' moves to the start on the next line. 'q' ends recording the macro.

I can then replay the macro with '[email protected]' (replay macro in register q 8 times).

What does everyone else think about macros?

In my opinion, macros should be recorded keyboard input that can be played back.

const char *hexChars = "0123456789ABDCEF";