DigitalNomad
DigitalNomad

Reputation: 1031

Vim Format Text (Break line) at a fixed length intelligently

I have acquired a huge codebase in which the previous developer(s) did not follow 80 characters length. I am trying to for a really long lines into multiple lines with continuation. This is a IDL language.

Before

test_function, variable1, variable2, variable3, variable4, variable5, variabl6, variable7, vaiable8, variable9, variable10, ...

After

test_function, variable1, variable2, variable3, variable4, $
    variable5, variable6, variable7, variable8, variable9,  $
    variable10

I have used formatprg and par for formatting a paragraph. I am looking for a way so that it will break the line (intelligently) at about 80 characters at comma (and possibly add continuation ($) sign). It will be a huge time saving, as I do not have to break these 1000's of lines to 80 characters manually.

Thank you.

Upvotes: 1

Views: 1168

Answers (2)

ryuichiro
ryuichiro

Reputation: 3865

I don't know how to set it by formatting options, but this workaround could do the job

:%s/\%>68c \%<78c/ $\r/

It means substitute(%s) matched space () between columns 68 (%>68c) and 78 (%<78c) by space and $ and line break (\r). 78 because of appending two characters at the end of the line.

:h \%c


There are also comments which would be nice to keep, so before you run first substitution, run this command

:%s/\(^\s\{-};\).*\%>68c\zs \%<78c/\r\1 /

It means substitute on lines which begins with ; (and possibly some whitespaces before(\s\{-})), start the match (\zs) after column 68 till 78, take the beginning of the line till ; (\(^\s\{-};\)), and pass it (\1) after line break.

:h \s :h \{ :h \zs :h \(

Upvotes: 0

user5152421
user5152421

Reputation:

This is the answer of your problem: https://stackoverflow.com/a/1272247/5152421

Vim does this very easily.

gq{motion} % format the line that {motion} moves over
{Visual}gq % format the visually selected area
gqq        % format the current line
...

I'd suggest you check out :help gq and :help gw.

Also setting textwidth (tw) will give you auto line break when exceeded during typing. It is used in gq too, though if disabled gq breaks on window size or 79 depending on which comes first.

:set tw=80

Upvotes: 3

Related Questions