Sanitizing inputs for markdown strings

We have some user-facing strings that include earlier user input in them and need some styling. We thought we could use markdown for that but it turns out that when you use AttributedString(markdown:options:baseURL:) with an interpolation it will first resolve the string and then do the markdown formatting, which means that the inputs go in unsanitized and the formatting may end up completely out of whack.

SwiftUI.Text actually does the right thing here but we need to do the processing through attributed strings since some will display on UIKit and we also do some other formatting that SwiftUI doesn’t support out of the box.

Is there some obscure markdown parsing option or syntax to make sure that a part of the string or an input gets treated verbatim instead of processed for markdown styling?

Failing that any pointers to implemented solutions would be welcome. Thanks!

Foundation itself currently doesn’t have an API for escaping text to prevent markdown parsing. You could look for alternate APIs to escape the markdown text (I don’t know offhand if there is something that would be safe to rely on). But if you’re looking for a solution with Foundation APIs, you could use interpolations with a custom attribute to interpolate after markdown parsing. For example, instead of interpolating user input into the strings directly you could interpolate text like ^[to be replaced](interpolation: 1) etc. for each interpolation, and then after calling AttributedString(markdown:) you could iterate over the text looking for your custom replacement attribute and replace its value with the text that should be interpolated (and apply any attributes from the “to be replaced” text to the interpolated text). This way you can be sure user input isn’t taken into account by only interpolating it after the markdown is parsed.

Thanks! If there is no way to do this straight with Foundation consider the initial post a feature request as well :wink:

I considered something similar to what you describe, and it would solve well for string interpolations in code. I’m however unsure of how I would deal with LocalizedStringResource values, since most of the interpolations to display will come in that format and I can’t think of a bottleneck to process the localized string’s interpolation that I can easily access.