Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change wrap width in a text file using Vim

I want to format srt subtitle text files to avoid wrapping problems on my media player.

I need to set a line wrap width to a number of characters e.g. 43

I can do this with Editplus, its a built in function and works well. The reason I want to do it in Vim, firstly Editplus is only available on the PC and the secondly Vim is badass.

I have found the following solution on the net..

:set tw=43
gggqG

It does work, but not exactly how I want it.

E.g.

I have this text:

557
00:47:39,487 --> 00:47:42,453
I will have to complete some procedures,
and I asked you to check out what they are for me

after I format it, I get:

557 00:47:39,487 --> 00:47:42,453 I will
have to complete some procedures, and I
asked you to check out what they are for
me

It seems to ignore line breaks/CRs. As you can see the "I will" has been added to the first line.

How do I get it to not ignore line breaks?

EDIT: apoligies about the formatting, first time using stackoverflow!

like image 293
Fred Avatar asked May 14 '26 04:05

Fred


1 Answers

You could use the whitespace option of formatoptions and make the lines you want to wrap end in whitespace.

:set tw=43
:set fo+=w
:g/^\a/s/$/ /
gggqG

The third line adds a space on the end of any line starting with a letter and fo+=w stops gq from joining lines that don't end in spaces.

See:

:help fo-table
:help 'formatoptions'
:help gq
:help :g

Edit in response to comments

:g/^\a/s/$/ /

This translates to:

:g/   " Search the file
^\a   " For lines starting (^) with an alphabetic character (\a - equivalent to [A-Za-z])
/     " Then on each line that the regexp matches (i.e. each line starting with an alphabetic character)
s/    " Substitute...
$     " The end of line (zero-width match at the end of the line)
/ /   " With a space (slashes are delimiters)

The global (:g) command will only operate on the current file, but the textwidth and formatoptions lines will last for the whole session. If you want those options to only be used on the current buffer, use :setlocal instead:

:setlocal tw=43
:setlocal fo+=w
:help :setlocal
like image 112
DrAl Avatar answered May 17 '26 01:05

DrAl