I am working on InDesign UXP plugin. So, it should be able to change text and keep exact formatting. The best way I get it is changing paragraph.contents value.
It looks well for the text with the same characters encoding. For example,
English → Italian
or German → French
flows work pretty well. If I try to replace the text, for example, from English to Ukrainian, InDesign doesn’t preserve text styles just like styles from the previous paragraph is applied on the current one. What is the difference for InDesign here?
I have no idea if what you’re experiencing is a bug because of the language, but I always thought that if you wanted to maintain the formatting you should rather than using the paragraphs’ contents you should instead be traversing the story’s .textStyleRanges’ contents
Thank you for your response. Yes, i’ve found .textStyleRanges to use them instead of paragraphs for better styles preserving. Little adjusted my code to try this, but the issue is not solved. I am getting a similar result if the text was in English and is translated into cyrillic alphabet language.
When you replace paragraph.contents, you’re also replacing the return character at the end of the paragraph. That means that you’ll lose the formatting applied to the paragraph by its paragraph style. It’s most likely that you’ll get the formatting of the character that precedes the text you’ve replaced. This is also true if you replace the textStyleRange containing the return character.
Basically, return characters are how InDesign knows that a specific piece of text is a paragraph.
You can avoid this problem using text ranges. Something like (off the top of my head) texts.itemByRange(paragraph.characters.item(0), paragraph.characters.item(-2)) should work (for all but the last paragraph in a story, -2 will be the character preceding the return).
Also, remember that textStyleRanges can span paragraphs.
My couple of cents: instead of changing a text object’s (e.g. a paragraph) contents, try the find-change methods which are available for any text object (even for one word/character). This should keep the formatting.