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");