Replacing NSTextView text programmatically without affecting its style and format

In the previous post I discussed the addition of Dynamic Date parsing to MarsManaged. In a nutshell: actions containing certain keywords (i.e. today, tomorrow, next month) are automatically converted to target dates. 

High level, the flow is as follows:

Screen Shot 2022 05 28 at 12 00 43 PM

Nice right? Well, I quickly discovered an unexpected surprise: the TextView format was being lost when the keyword replacement happened.

BugReplacement

After some digging I found the culprit ->  textView.string.replaceSubrange([…])

Every time that line of code was called, TextView would lose its attributed format.  

To deal with this, I initially considered reformatting the CARD every time a keyword was replaced. That would work of course, but it’s not clean nor efficient… Thankfully, after some digging, found a better solution to the problem by using textStorage attribute instead of string. That completely prevents the loss of format, so no need to do anything else.  

Updated replacement code -> textView.textStorage!.replaceCharacters(in: […]) 

And here’s the result:

LaunchToVenus32

Thoughts, suggestions? Reach me @MarcMasVi

Marc