4

I want to join all the lines within a {} block.

{
  'a': 1,
  'b': 2,
  'c': 3,
}

⬇︎

{ 'a': 1, 'b': 2, 'c': 3, }

Since J doesn't take a range, like d or c, the best command I found to do this is going through virtual mode: Va{J.

Is there a nicer way to do the same?


This is not a duplicated of Why doesn't gJip turn a paragraph into a line? since that question doesn't ask how to turn a paragraph into a line. The proper answer of that question is "gJ doesn't work like that".

  • 1
    J takes a count...that's not what you're looking for? Note that d and c don't take ranges. They take motions (including count). Do you mean motion rather than range? (there's also :join which takes a range and/or a count so if you nmap that it might work for you.) – B Layer Apr 27 at 10:53
  • Rephrasing the first question, is 5J from the opening `{`` not to your liking? – B Layer Apr 27 at 11:00
  • 1
    Does this answer your question? Why doesn't gJip turn a paragraph into a line? – filbranden Apr 27 at 11:25
  • @BLayer The ranges I have aren't always 5 lines long. – Martín Fixman Apr 27 at 16:15
  • Of course not. That was the solution to your example. You need to know the count. You didn't give enough information to determine whether [count]J was acceptable so I asked. – B Layer Apr 27 at 20:26
5

This is called "a motion". Even though linewise motions result in a line range.

Normally, it's enough to do 5J and there's no need for "join" operator. However, if you really want it, you can make use of :h g@ and :h 'opfunc' A simplified example:

" very basic "join" operator
nnoremap <silent>J :set opfunc=OperJoin<CR>g@
function! OperJoin(type) abort
    '[,']join
endfunction

Now Ja{ will do the job.

| improve this answer | |
2

Well, since J works in visual mode...

va{J

More generally v[motion or text object]J. Normally I would say this is a bit of an anti-pattern (prefer [operator][motion or text object]), but there is no join operator.

Here, even v%J should work


Alternately, use :join, which takes a range, and ranges can be quite powerful:

.,/}/join
| improve this answer | |
  • Thanks for this most useful suggestion! – NateB Oct 1 at 19:25
1

The commandline command you're looking for is 'j':

:1,5j
| improve this answer | |
  • I can't so this within an arbitrary {} block though. – Martín Fixman Apr 27 at 16:16

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.