0

I have a long text file (300 lines), and I would like to format it so each line is not longer than 50 characters. For example, we have:

I have a really long text, I have a really long text, I have a really long text
I have a really long text, I have a really long text, I have a really long text
I have a really long text, I have a really long text, I have a really long text

And the goal is for it to look like :

I have a really long text,I have a really long
text, I have a really long text I have a really
long text, I have a really long text, I have a 
really long text, I have a really long text, I
have a really long text, I have a really long
text, I have a really long text

Is there a way to do it besides setting 'textwidth' and gww? Using backrefernces?

2
  • 1
    Welcome to Vi and Vim! Is there a reason 'textwidth' and gw (or gq) is not useful you? AFAIK, that's the de-facto length-formatting tool. gqap would do exactly what you need.
    – D. Ben Knoble
    Commented Oct 24, 2019 at 2:27
  • In the first line of your goal text, there is a comma with no space after it. Is that just a typo?
    – Rich
    Commented Oct 24, 2019 at 9:09

1 Answer 1

2

There are a couple of ways to approach this, however each one has its own drawbacks:

  • There is no really good way to re-format a list of strings programmatically according to a different textwidth value. Your current best chances are basically to set the 'textwidth' option and reformat using gq (this can be done in another window to leave the current option value in the current window alone).

  • You can also try to use some basic regexp magic, but be aware, you most certainly need to post process the result. Try this one:

    %s/\(.\{50\}\)/\1\r/g
    

    This will add a newline after 50 characters, however it will add newlines within a word and the result may not look visually pleasing. Slightly better would be this approach, which tries to find a space after 40 characters and break the line on that one:

    %s/.\{40\}\zs\s/\r/g
    
  • Finally, you can also try to implement your own textformatting algorithm according according to your needs. Be aware however, there is no VimScript function to reformat according to what Vim would do internally. So you have to re-implement it in pure VimScript and this can be become a can of worms once you start this way. I recently did this with the official vim-xml-runtime plugin and I am not yet satisfied.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.