1

When a line becomes too long, I would like to wrap the function call with a "one argument per line" syntax:

For the example: :set textwidth=50. Given:

    long_function_name(argument_one, argument_two, argument_three, { complex: 'argument' })

I want a command, function or mapping, preferably just gq, to turn this into:

  long_function_name(
    argument_one,
    argument_two,
    argument_three,
    { complex: 'argument' }
  )

Currently, hitting gq wraps it to:

  long_function_name(argument_one, argument_two,
                     argument_three, { complex:
                                       'argument'
  })

Which is hard to read and messy. E.g. the Rust styleguide uses the one-arg-per-line formatting

This example is Ruby code, but I presume this hardly differs and would be the same for e.g. Rust or C; So if the Ruby-ism, the { complex: 'argument' } is unsupported, I don't mind some manual editing afterwards, in order to fix this.

I've played around with cinoptions as explained in this stackoverflow answer but either don't understand that feature, or fail to configure it to do what I want.

  • 1
    Welcome to Vi and Vim! Unfortunately, gq is (by default) a dumb formatter. You can set formatprg to a program of your choice, however, if you have a good ruby/rust/go/etc. formatter (an ftplugin may be an appropriate place, using setlocal) – D. Ben Knoble Nov 11 '20 at 15:42
  • Thank you @D.BenKnoble, do I understand it correct that gq will use formatprg if set? – berkes Nov 11 '20 at 16:46
  • 1
    yes, :help 'formatprg' – D. Ben Knoble Nov 11 '20 at 17:18
1

A simple way to go is to setlocal formatprg=... whatever formatter you want to use. This option controls the gq operator. E.g., for ruby, I would put something like

setlocal formatprg=...

in ~/.vim/after/ftplugin/ruby.vim. Make sure to update b:ftplugin_undo, too.

Note that not many "formatting programs" play well with formatting a single line or even some regions, as they often implement full parsers: in this case, it can be more appropriate to set formatprg and remap gq:

nnoremap gq mzgggqG`z

which reformats the whole file without moving the cursor. (Why? Formatting is hard, error recovery is harder. So most programs are designed only to format entire, conforming ASTs—this makes them unusable on small, incomplete program fragments like a single line. Some do this hard work, though. The point is, gq can operate on (nearly) arbitrary text; not all formatprgs can.)


See also the "fine print":

The program must take the input on stdin and produce the output on stdout.  

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.