1

Is there a quicker way to create more entries of form { "name": FIELD_NAME, "type": "string" } from a list of words down below, than recording a macro to process each word and then pasting the result in place?

{
  "namespace": "my-space",
  "type": "record",
  "name": "Transaction",
  "fields": [
    { "name": "transaction_id", "type": "string" }
  ]
}

# Fields
first_name
last_name
amount
currency
transaction_date

I was hoping for an alternative approach where I could use a template string and then use the list of words to create substituted entry for each, so:

{ "name": "PLACEHOLDER", "type": "string" } => { "name": "first_name", "type": "string" }
                                               { "name": "last_name", "type": "string" }
                                               ...

I'm happy to use the macros, but something along the lines of the above would be more intuitive for me (and hopefully for others, too).

2

Have you considered using :substitute? First, start with this:

{ "name": "\1", "type": "string" }
\(\w\+\)

first_name
last_name
amount
currency
transaction_date

Now, on line one, yank to register a: 1G^"a$. On line two, yank to register b: 2G^"b$. Then perform the substitute on the appropriate lines:

:4,8s/<c-r>b/<c-r>a/<cr>

Note: <cr> means the enter key and <c-r> means ctrl+r

Result:

{ "name": "first_name", "type": "string" }
{ "name": "last_name", "type": "string" }
{ "name": "amount", "type": "string" }
{ "name": "currency", "type": "string" }
{ "name": "transaction_date", "type": "string" }

You could have also used visual block mode, but this method more easily generalizes to multiple fields; you can use \1, \2 up to \9.

  • I see you've edited the answer - your previous approach would work if you add a space, e.g. :1y a<cr> – LordTwaroog Oct 3 '17 at 16:29
  • 1
    Other than that, I really like your approach here, especially when it allows you to capture multiple fields. Thanks! Let's see if anyone comes up with an alternative, otherwise I'll accept the answer. – LordTwaroog Oct 3 '17 at 16:31
  • @LordTwaroog indeed forgot the space originally. With the space, it works, but requires you to remove the ^M when putting into the command line, which is confusing for a newbie, so I decided 1G^"ay$ is more easily understood. – Mass Oct 3 '17 at 16:38
  • I see - I didn't experience that, but I'm assuming that's because I'm on a Mac, not Windows. Or maybe that's a NeoVim thing. – LordTwaroog Oct 4 '17 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.