Vim: generate match statement with every constructor of a variant type

merlin
text-editor
vim

#1

Hello,

I’ve been often running into a pattern where I need to write out a match statement with every constructor of a variant type. It gets a bit annoying when there are a lot of constructors. I’m using vim with merlin, and I was wondering if there existed a way for me to automate this. I’d be open to writing a function that could look up the type of a variable, and then generate a bunch of match cases, something like this:

type test_type = C1 | C2 | C3 | C4
match test with

Then with the cursor over test, I would type something like :My_function_name, and then it would generate this:

match test with
| C1 ->
| C2 ->
| C3 ->
| C4 ->

I guess I thought I’d post here to ask for some pointers. I imagine writing some kind of macro would be straightforward, but is there a way I can look up the types? In particular, what can one do if they’re defined in another file? Maybe I could piggyback this off of merlin somehow? Not sure. Would love some tips. Maybe it’s more trouble than it’s worth?

EDIT: writing this out, I’ve realized there would be no way to tell what the type of test is. Maybe I could make a function that asks for the name of a type, and the variable, and then it would just generate the complete match statement. I guess now I’m just wondering if maybe such a feature exists somewhere on the internet, or I guess I’d be interested in hearing if other people do something fancy with this.


#2

Merlin provides a merlin destruct command to do that. I don’t know how it is called exactly in Vim. But it should be visible in merlin’s help.


#3

I think :MerlinDestruct does exactly what you are asking for. You don’t need to write the match...with at all, it will get filled in.


#4

Oh, perfect, thanks!