Changing the width of the wrapper in a text file using Vim
I want to format srt subtitle text files to avoid transfer problems on my media player.
I need to set the line break width to the number of characters, eg. 43
I can do this with Editplus, its built in function and it works well. The reason I want to do this in Vim is firstly because Editplus is only available on PC, and secondly because Vim is a badass.
I found the following solution on the net.
: set tw = 43
gggqG
It works, but not exactly how I want it.
eg.
I have this text:
557
00: 47: 39.487 → 00: 47: 42.453
I will need to do some procedures
and I asked you to check that they are for me
after i format it i get:
557 00: 47: 39.487 → 00: 47: 42.453 I will
have to do some procedures and I asked you to check what they are for me
Line breaks / CRs seem to be ignored. As you can see, "I want" has been added to the first line.
How do I make it not ignore line breaks?
EDIT: apoligies about formatting, first time using stackoverflow!
source to share
You can use the whitespace option for formatoptions
and make the lines you want to wrap in spaces.
:set tw=43
:set fo+=w
:g/^\a/s/$/ /
gggqG
The third line adds a space at the end of any line that starts with a letter and fo+=w
stops gq
lines that do not end with spaces from concatenating.
Cm:
:help fo-table
:help 'formatoptions'
:help gq
:help :g
Edit in response to comments
:g/^\a/s/$/ /
It means:
: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)
Global ( :g
) command will work only with the current file, but string textwidth
and formatoptions
will last for the entire session. If you want these options to only be used in the current buffer, use instead :setlocal
:
:setlocal tw=43
:setlocal fo+=w
:help :setlocal
source to share
If the only lines you want to wrap are those that start with text (ignore those that start with numbers), you can use the following.
:g/^[a-zA-Z]/normal gqq
This will run p00ya command on every line of text in the file.
source to share
With the following text (i.e. only 3 lines):
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
Use gqq
(format current line) on the third line after installation tw
. Paragraph formatting will not work as vim will treat all 3 lines as part of the same paragraph (paragraphs end with a blank line).
source to share