Script for applying character style on text after inserting it from variable


I need a script for InDesign which do the following: insert text string from variable and format it with existing character style.

The previous to last string does not working in my attempt:

var myNewText = "someText";
var myStyle = app.activeDocument.characterStyles.item("Inserted Text");
myTextFrame = app.selection[0];
firstInsertionPoint = myTextFrame.insertionPoints[-1].index;
myNewText.appliedCharacterStyle = myStyle; // THIS NOT WORKING
myTextFrame.contents += myNewText;
3/18/2016 2:57:00 PM

Accepted Answer

The problem is that you are trying to format the string - which is not an object in InDesign and therefore cannot be formatted via InDesign styles.

Instead you need to first add the string to the contents as you did in your last line, which will transform your string into real text objects (like words, characters, etc.) which you can format then.

To figure out which parts of the text in your text frame to edit you need to find two indices, those where the formatting begins and ends, the most appropriate would be on a character level. The start index will just be your last character + 1 and the end index is this start index plus the length of the string to add (-1).

The character style does not necessarily be saved in a variable first and the firstInsertionPoint does not do anything in your script. I edited your script to fix your issue and to make a bit more clear (I hope), what's happening. It should work this way.

var myNewString = "someString";
var myTextFrame = app.selection[0];

var styleStartIndex = myTextFrame.characters.lastItem().index + 1;
var styleEndIndex = styleStartIndex + myNewString.length - 1;

myTextFrame.contents += myNewString;
myTextFrame.characters.itemByRange(styleStartIndex, styleEndIndex).appliedCharacterStyle = "Inserted Text";


Ok, since you need to insert the text at the current text cursor position, the script needs to look a little different. From your original code I assumed you need to insert it at the end of the text frame. I'll leave in my original answer with the explanation, as it might help people who have similar problems.

Here is the modified code that should do, what you actually want to do:

var myNewString = "someString";
var myTextFrame = app.selection[0].parentTextFrames[0];

var styleStartIndex = app.selection[0].index;
var styleEndIndex = styleStartIndex + myNewString.length - 1;

app.selection[0].contents = myNewString;
myTextFrame.characters.itemByRange(styleStartIndex, styleEndIndex).appliedCharacterStyle = "Inserted Text";
4/7/2016 10:04:00 AM