Santhosh N
Santhosh N

Reputation: 157

Change an existing C source file to 80 column width in Vim

I have several C files, in which the lines exceed more than 80 columns. I need to wrap them to a 80 column boundary and at the same time maintain proper C syntax. Is this possible in Vim?

I have seen several solutions on the web for doing it on a normal text file. Also, have found tricks to do wrapping in a C file, which is about to be edited. But not for existing C files.

Any tools for achieving this apart from Vim are also welcome.

Upvotes: 1

Views: 564

Answers (2)

user1146332
user1146332

Reputation: 2770

If you edit c-sources it is likely that you set the cindent option. Unfortunately the textwidth option doesn't work with cindent.

For your purpose artistic style, although it's a very nice program isn't recommended either since it doesn't support the breaking of long lines.

To get what you want i use gnu indent and set equalprg to

let &equalprg= "indent -l80 -i" . &shiftwidth . " <optional args>"

and add

map <leader>i mzgg=G`z

to my ~/.vimrc. With that pressing <leader>i reformats the whole file without changing the cursor's position.

Another possibility would be to add an autocommand that indents the source on every write, like

autocmd BufWrite *.c execute "%!".&equalprg

Upvotes: 3

Daan Bakker
Daan Bakker

Reputation: 6332

With vim you could do that with :set tw=79 and gggqG. However, it is not context-aware so you will need to restore certain lines (for example, lines with long strings in them).

For an external tool you might want to look at Artistic Style, which reformat lines where reformatting is not hard (for example, lines containing a {).

Upvotes: 2

Related Questions