1

For example, suppose I have this line of JavaScript:

console.log(
   "This is a really long line that I want to format, and it is inside of a quote"
)

I'd like to select the quote line in VISUAL-LINE mode, the pres gq to format it, but it doesn't work. The result is something like this:

console.log(
  "This is a really long line that I want to
  format, and it is inside of a quote"
)

but I was hoping that it would be something like this:

console.log(
  "This is a really long line that I want to "+
  "format, and it is inside of a quote"
)

so that the result is still a proper string.

Is it possible to do this with Vim?

1

For what it is worth: :h gq explains that you have 3 ways to format your code with gq

1. If 'formatexpr' is not empty the expression is
   evaluated. This can differ for each buffer.
2. If 'formatprg' is not empty an external program
   is used.
3. Otherwise formatting is done internally.

Let's begin with the third option: the internal formatting is controlled by 'formatoptions' and :h fo-table shows that we can't achieve what you want to do with built-in options.

Now you have two choices: either find an external program which will format your code as you want or write a function used by formatexpr.

About formatexpr the help (:h 'formatexpr') doesn't tell us a lot about how to write the function. You can have a look at this Vim dev mailing list post and this answer to get some very basic examples. I think writing such a function might be a lot of trouble since you would need to re-implement the current behavior of gq and add the quotes formatting.

So I would say that your best bet is to find an external tool to do the formatting and set your formatprg properly. (Remember to set it in an ftplugin so that it only affects javascript code.)

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.