[comp.editors] awk format pgm

dbar@ecst.csuchico.edu (David Barrett) (04/13/91)

Who is good with awk?  I have taken an awk script from page 120 of The Awk
Programming Language, by Aho, Kernighan and Weinberger, and tried to get
it to work.  No luck.  The program is called 'fmt' and is intended
to even out the ragged right margin of a text file.  (It does not justify
the lines, only adjusts line lengths to length less than 60 characters.)

Here is the script:

/./   { for (i = 1; i <= NF; i++) addword($i) }
/^$/  { printline(); print "" }
END   { printline() }

function addword(w) {
	if (length(line) + length(w) > 60)
		printline()
	line = line " " w
}

function printline() {
	if (length(line) > 0) {
		print substr(line, 2)
		line = ""
	}
}

After storing this script in file "fmt", I give the command 
"awk -f fmt sourcefile", where sourcefile is a text file to be formatted.
I get compiler messages from awk, as follows.

awk: syntax error near line 2
awk: illegal statement near line 2
awk: syntax error near line 3
awk: illegal statement near line 3
awk: bailing out near line 5

If this little script worked (and also were implemented more conveniently
as a shell script called 'fmt') it could be useful as a margin-adjust macro 
that could be invoked from vi command mode.  e.g. to adjust margin of a 
paragraph from which you have just added or deleted words from, press 
CNTL-A, where CNTL-A is defined in .exrc file as as: 

                              map ^A  !}fmt

and ^M is the sequence cntl-V cntl-<CR>

To format whole file, substitute G for }.

tchrist@convex.COM (Tom Christiansen) (04/13/91)

You have an awk that doesn't grok functions.  Get one that does, or 
run it through a2p so you can run perl on it.  Or just get the BSD
version (in C) off uunet.

--tom