MACRO: WordWrap Text

Macro Library WordWrap Text

Requires: OS/X Yosemite or later.

WordWrap Text.v1.0.kmmacros (17.1 KB)

##PURPOSE:

This macro takes a string, and a maximum line width, and word-wraps the text into multiple lines. Obviously, the result is only really useful when used with a fixed-width font, like a text editor.

##EXAMPLE:

Original text:

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Result, wrapped to 60 characters:

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS 
ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO 
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER 
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, 
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
OF THIS SOFTWARE.

##USAGE:

There's two macros here. One gives you a prompt so you can enter values and get the results right away. The other is a sub-macro you can call from one of your macros.

###WordWrap Text (Prompt)

Result:

###WordWrap Text (Sub-Macro)

Execute the macro, like this:

You pass the text, followed by "|", followed by the width, followed by "|", followed by the name of the variable to receive the result.

###DETAILS:

This macro uses a very cool regular expression I stumbled across on the web a while ago. The macro uses JXA to build the regex using the width you specified.

Here's an example of the regex, with a hard-coded width of 80:

var matches = str.match(/.{1,80}(\s|$)|\S+?(\s|$)/g);
return matches.join("\n");
3 Likes
var matches = str.match(/.{1,80}(\s|$)|\S+?(\s|$)/g);
return matches.join("\n");

Great Macro/RegEx Dan! :thumbsup:
Thanks for sharing.

For those of you who want to learn RegEx, here is the explanation from Regex101.com.
Although this RegEx is very short, it is very powerful and definitely an advanced pattern.

1 Like

FWIW there’s a parameterized variant on that (word-wrap by Regex in JS) theme on Rosetta Code:

https://www.rosettacode.org/wiki/Word_wrap#Simple_regex

I don't see any material difference from the actual JXA code that @DanThomas used.

I didn’t show the code from the macro I posted, but it is, in fact, a function with a parameter. I only showed the regex in the post because I thought it was cool.