InDesign Script to Auto Apply certain CharStyle when Punctuation is used with specific Font
I'm using a custom font for my headers in InDesign called Xillian Family, which doesn't have any punctuation marks. If I need to use punctuation within a header, I apply a font called Yeseva One. I'm trying to automate this process by writing an indesign script that will automatically apply a Yeseva One character style to any punctuation within a text range or text frame that uses Xillian Family. I tried using the script below, but it's not working.
// Define the font name and the character style name
var fontName = "Xillian Family";
var cStyleName = "Yeseva One";
// Get a reference to the font and the character style, and create the character style if it doesn't exist
var font = app.fonts.itemByName(fontName);
var cStyle;
if (app.activeDocument.characterStyles.itemByName(cStyleName) == null) {
cStyle = app.activeDocument.characterStyles.add({name: cStyleName, appliedFont: "Yeseva One"});
} else {
cStyle = app.activeDocument.characterStyles.itemByName(cStyleName);
}
// Define a function to apply the character style to punctuation marks in a text range
function applyCharacterStyleToPunctuation(textRange) {
for (var j = 0; j < textRange.characters.length; j++) {
var character = textRange.characters[j];
// Check if the character is a punctuation mark
if (/[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]/.test(character.contents)) {
// Check if the text range still exists
if (textRange.isValid) {
// Apply the character style to the punctuation mark
character.appliedCharacterStyle = cStyle;
}
}
}
}
// Define a function to handle the "afterSelectionChanged" event
function onSelectionChanged(event) {
var selection = app.selection[0];
// Check if the selection is a text frame or text range
if (selection instanceof TextFrame || selection instanceof InsertionPoint || selection instanceof Character) {
// Loop through all the text ranges in the selection
for (var i = 0; i < selection.textStyleRanges.length; i++) {
var textRange = selection.textStyleRanges[i];
// Check if the text range uses the Xillian Family font
if (textRange.appliedFont == font) {
// Apply the character style to punctuation marks in the text range
applyCharacterStyleToPunctuation(textRange);
}
}
}
}
// Add an event listener for the "afterSelectionChanged" event
app.eventListeners.add("afterSelectionChanged", onSelectionChanged);
