How to multi-line the import functions in {} in VIM?

Viewed 61

Sorry for the bad title but

With this code,,,

import { amethod, methodb, methodc } from '../../utils/mockData';

how do you make this

import {
  amethod,
  methodb,
  methodc
} from '../../utils/mockData';

with VIM? I mean how can I do it fast?

What I do is to

  1. go to the first method.
  2. press Enter
  3. go to the end of the method..
  4. press Enter...
  5. go to the second method. 6.... ...

It's so slow with VIM. Can we do this fast in VIM? I think I can this much faster with my mouse :(

import { amethod, methodb, methodc } from '../...';
         ^

4 Answers
f ;r<CR>;.;.;.

doesn't strike me as particularly slow. A tad too repetitive, maybe?

Here is a slightly smarter (but probably not that smart) approach:

ciB               " change in brackets
<CR><CR>          " insert two carriage returns
<Up>              " move up one line
<C-r>"            " insert previous content of brackets
<Esc>             " leave insert mode
:s/,/,\r/g<CR>    " put each symbol on its own line
=iB               " re-indent the content of brackets

that can be mapped for convenience:

nnoremap <key> ciB<CR><CR><Up><C-r>"<Esc>:s/,/,\r/g<CR>=iB

Or you can look for a proper plugin that handles corner cases gracefully.

@romainl had a good answer, but you can also use replace for this particular case:

:%s/\([,{]\)/\1\n/g

I have got this

import {
    amethod,
    methodb,
    methodc
    } from '../../utils/mockData';

Using this:

:%s/\v\{\zs( \w+,?)+ \ze}/\=substitute(submatch(0), " ", "\n\t", "g")


\v ............ very magic regex (avoid many backslashes)
{  ............ literal {
\zs ........... vim trick that marks the start of the pattern
(  ............ start of regex group 1
<Space> ....... literal space inside group 1
\w+ ........... one word or more
,?  ........... optional coma
+  ............ quantifier for the group (at least one)
<Space>
\ze ........... end of our vim search

The substitute function has three parts like a normal vim substitution and the submatch(0) corresponds to our regex, hence we are substituting in our regex one space for one line breake and two tabs.

With the cursor on line1 and col1, you can press this in normal mode:

f 4@=';r^M'

then press ENTER.

Note: for the ^M you press Ctrl-v then Enter

Related