How to wrap a text selection to a certain column width using AppleScript?
For e.g., let's say the following text is selected:
AppleScript is a scripting language created by Apple Inc. that facilitates automated control over scriptable Mac applications. First introduced in System 7, it is currently included in all versions of macOS as part of a package of system automation tools.
I'd like to run AppleScript (prefereably via some keyboard shortcut) on this selected text, which should wrap the lines to a specific width by inserting line breaks at the specific width. The width can be hard-coded in the script itself.
For e.g., if the width is 72, then, the above text should be changed to:
AppleScript is a scripting language created by Apple Inc. that
facilitates automated control over scriptable Mac applications. First
introduced in System 7, it is currently included in all versions of
macOS as part of a package of system automation tools.
Formatting the text to 72-chars is doable using fmt
utilty as fmt -w 72
. So, the individual steps would be:
- Get the selected text into AppleScript
- Run
fmt -w 72
on the text - Replace the selected text with output of
fmt
My primary use case is to wrap the emails that I compose to 72-char width on Apple Mail on macOS. Any other ideas (outside of AppleScript) to achive this goal are welcome too.
Thanks!
do shell script "echo " & srcTxt & " | fmt -w 72 "
, assuming that srcTxt is your string to break. In the terminal, it would look like this:echo AppleScript is a… | fmt -w 72
. By the way… you could probably add a keyboard shortcut to your service. And, you can accept your own answer although you probably won't gain any rep for it. But others may find the solution more easily if it is accepted.