r/emacs•
Jengu

Can emacs assist with writing switch/case over enum values?

I know I can press f3 a second time when recording a macro to insert an incrementing integer, which is pretty nifty, but what would be even cooler is if I could get the same effect but inserting enum values (not the integers but the named values) for a given enum. I suspect this information is already stored by ctags/etags/global (I use global) since they can do lookups of enum values, but I don't know how to get at that in elisp. This would be nice for generating switch/case statements in C. Anybody done anything like this already?

Posted Jun 22, 2010, 3:13 PM UTC

95
phob•

Put the enum values in your scratch buffer. Make sure your cursor is on the first line of the enums, and press f3. Copy the first line, switch back to your C code and type the first case statement, switch back to scratch and move your cursor one line down. Press f4.

Magic.

For more power, check out http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html for using replace-string-regexp for these sorts of tasks.

4
cstoner•

hrm, not exactly the clearest explanation of keyboard macros, but still a solution I wouldn't have thought of.

Upvote.

1
commonslip•

M-: (loop for i in (...) do (insert (format "..." ...)))

2
panghuhu•

I use this method, but I usually put the S-exp in the source code as comments, and surround the generated codes with special tags. This way it would be easy to delete the generated code and regenerate it again.

Another good thing is that you can type "C-x C-e" (which is the shortcut for eval-last-sexp) to run the code, even in C/C++ mode.

1
phob•

^ This method becomes way better than keyboard macros past a certain level of complexity. Also, it's very easily re-usable since you can save all your automations in an elisp file and edit them. Technically, you can save keyboard macros, but I haven't found it worth it.

1