views:

305

answers:

5

I'm preparing some documentation and need to format my source code with line breaks that need to appear in column 70 throughout the file.

The text editors I have only seem to have features to word wrap the source at this column.

I'm wondering whether I need to do this manually since - because of the varying length of the last word at the right-side end of the line - the line doesn't always end at the same place.

Any ideas?

A: 

Don't know of any editor that will do this, but you could run your files through this on the commandline:

perl -wlne'print $_ . (" " x (69-length($_)))' < infile > outfile

Or, if you're using Vim, you could select the text you want to modify in visual mode, and then type :! followed by perl -wlne'print $_ . (" " x (69-length($_)))' to pipe it through that Perl magic.

Hans W
A: 

What operating systems are available? On OS X, I think TextWrangler has a "hard wrap" option that should do what you want.

Tim Yates
Didn't know the term "hard wrap". That's what I needed. Thanks.
jts
A: 

I can't check it right now, but UltraEdit for Windows has a "column mode" that lets you do that kind of stuff. Not sure it can do the line breaks, but it's worth checking out (there's a trial version).

axel_c
+1  A: 

Certainly don't do it manually. You can do it in perl with:

perl -pe 's/(.{70})/\n$1/smg'

or you can do it in vim with:

:%s/\(.\{70\}\)/^M\1/g

(the ^M is entered with ^V-, and this will only work if there are no tabstops in the file. The tabstop issue is also true for the perl solution.)

Update: the comments are correct: this is a fairly naive approach. Vim also offers the formatexpr setting that is promising, but still doesn't seem to deal well with leading whitespace. Within vim, try (with cursor on line 1):

:set formatexpr=
:set textwidth=70
gqG

See vim's documentation on textwidth and ins-textwidth for more details.

William Pursell
Doesn't this just insert newlines every 70th character? I thought he wanted to add spaces to the end of each line, making the newlines all appear in column 70.
Hans W
@Hans: Yes, I'm allergic to regex so I trust that you're correct about what William is doing here. But, yes, you're right - I certainly don't want to drop a newline into the middle of a word so if your regex avoid this by adding spaces at the end, that would seem to be more in line with what I'm trying to do.
jts
A: 

VI can do this using

:set tw=69 (set the right line length)

gg (go to the top of the file)

gqG (reformat to the end)

Joel