# teaching machines

## Swapping first_second to second_first in Vim

When I write C code, I never know how to name functions. In an object-oriented language, my methods are verbs: add, insert, get, swashbuckle, and so on. The subject or indirect object of these verbs is an instance of the containing class, making my code read like English sentences: vector.add, list.insert, image.get, swashbuckler.swashbuckle.

In C, which has one global namespace, functions simply can’t be named generically. Add, insert, and get are out of the question. Usually, I add the name of the data structure to the function: vector_add, list_insert, image_get. However, sometimes I get the order swapped in my head, and type in insert_list or free_stack or some such.

It happens often enough that I wrote a Vim macro to turn free_stack into stack_free:

nmap <Space>_ dt_ea_<ESC>pbx

I hit <Space>_ with the cursor in the offending function identifier and the tokens get switched around. Let me break down this command into its steps:

1. Delete (d) text starting at cursor right up until underscore (t_). The results are stored in Vim-tracked register variable.
2. Go to the end of the identifier under the cursor (e).
3. Go into insert mode after the cursor position (a).
4. Insert an underscore (_).
5. Go into command mode (<ESC>).
6. Paste the contents of the register (p).
7. Back up to the beginning of the identifier, to the underscore we didn’t delete (b).
8. Delete the character under the cursor, the underscore (x).