One thing I find myself doing often is using visual mode to select a block containing a long function definition containing one or more keyword arguments, and then using gq to reformat the code across multiple lines.

some_function <- function(keyword_argument1 = "foo", keyword_argument2 = "bar") {


some_function <- function(keyword_argument1 = "foo", 
                          keyword_argument2 = "bar") {

If I'm lucky, the function keyword arg pairs happen to line up with the maximum column width, and the reformatted function definition looks clean.

Just as often, however, the split happens to occur in between the "key" and "value" parts of the keyword argument pairs, and you end up with the function argument on one line and the value on the next, e.g.:

some_function <- function(keyword_argument1 = "foo", keyword_argument2 =
                          "bar") {

This is particularly a problem for languages like R, where style conventions encourage you to keep a space before and after the "=" in the kwarg pairs.

The result is that I end up spending a lot of time first reformatting things with gq, and then going back and manually adjusting the text so that the kwargs pairs are together.

Does anyone happen to know of a way to avoid this behavior so that matched keyword-value pairs are kept together when reformatted across multiple lines?

  • 2
    This can be done, you need to set the 'formatexpr' option to a function that knows how to wrap the lines while keeping the k/v arguments together. It's doable, but it can be quite complex to do so... Sorry I don't have the time to go all the way there to write an answer for you, but I wanted to give you pointers, in case you're interested in pursuing that yourself... – filbranden Sep 12 '19 at 3:57
  • 1
    If you want an example, see XML formatexpr set here to this function. – filbranden Sep 12 '19 at 4:04

Your Answer

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

Browse other questions tagged or ask your own question.