Wrap text to a certain width

Lately I wrote an AppleScript for my current employer, which reads text files generated by a lab device and then reformats the content to fit into a PDF report for our valued customers. And for this AppleScript I needed a function to wrap text to a certain width (e.g. 80 characters per line).

But I was too lazy/busy to write my own routine and so (once again) used a Python helper script utilizing the built-in «textwrap» module. It works quite well and if you also need to re-wrap text sometimes, then I invite you to test and inspect the Script bundle below:

wraptxt - Easily wrap text to a certain width (ca. 6.5 KB)

The script was successfully tested on Intel & PowerPC based Macs running Mac OS X 10.5.3.

Happy text wrapping!

Important: Opening and saving the below script code in Script Editor won’t result in a usable AppleScript! That is because the AppleScript internally relies on a Python helper script, which is located inside its Application bundle. Therefor please download the complete script here.


-- sample text, which is going to be wrapped
set txt to "This is my boss, Jonathan Hart, a self-made millionaire, he's quite a guy. This is Mrs H., she's gorgeous, she's one lady who knows how to take care of herself. By the way, my name is Max. I take care of both of them, which ain't easy, 'cause when they met it was MURDER!"

-- getting a list of paragraphs matching the chosen text width
-- we also choose to replace whitespace
set wraplines to my wraptxt(80, true, txt)
-- joining the paragraphs to create a new text
set countwraplines to length of wraplines
set newtxt to ""
repeat with i from 1 to countwraplines
	set wrapline to item i of wraplines
	if i is not equal to countwraplines then
		set newtxt to newtxt & wrapline & return
	else
		set newtxt to newtxt & wrapline
	end if
end repeat
-- there we are!
return newtxt

-- I am wrapping given text so every line is at most «maxwidth» characters long.
-- You can also choose to replace whitespace or not.
-- I return a list of paragraphs, without final newlines.
-- (I rely on a Python script utilizing the «textwrap» module)
on wraptxt(maxwidth, replacewhitespace, txt)
	set pyscriptpath to POSIX path of (((path to me) as Unicode text) & "Contents:Resources:wrap.py")
	if replacewhitespace is true then
		set replacewhitespace to "1"
	else
		set replacewhitespace to "0"
	end if
	set wraplines to paragraphs of (do shell script "/usr/bin/python " & quoted form of pyscriptpath & space & maxwidth & space & replacewhitespace & space & quoted form of txt)
	return wraplines
end wraptxt