Copy link to clipboard
Copied
Hello everyone, I would like to ask a simple technical question about scripting in Illustrator. How can I insert specified text at the current cursor position using a script in Illustrator? Alternatively, when using the Type tool to select a portion of text, how can I use a script to replace that text with specified text?
Thank you!
Copy link to clipboard
Copied
Hi @Aprking, I don't know the answer to the first question. I don't think we have access to mouse events via scripting. It may be possible via an elaborate (and hacky) use of Script UI, but I wouldn't get my hopes up. I think you'll need SDK for that one.
As for the second question, you can do something like this:
(function () {
var myContents = 'Replacement Text';
var doc = app.activeDocument,
item = doc.selection;
if ('TextRange' !== item.constructor.name)
return alert('Please select some text and try again.');
item.contents = myContents;
item.select(true);
})();
- Mark
Copy link to clipboard
Copied
Thank you very much to @m1b for the help, the problem has been resolved
Copy link to clipboard
Copied
I added two lines to the script to change item.name:
var newName = 'New Text Box Name'; item.name = newName;
However, it didn't work because the text box is not in a selected state. What are some good ways to solve this problem? Thank you!
Copy link to clipboard
Copied
Hi @Aprking, it doesn't matter what is selected. Remember that `item` is a TextRange, not a TextFrame (in my code I should have called it `textRange`, not `item` since I knew it was going to be a textRange).
To get the textRange's container takes a little extra work. See below.
- Mark
(function () {
var myContents = 'Replacement Text';
var doc = app.activeDocument,
textRange = doc.selection;
if ('TextRange' !== textRange.constructor.name)
return alert('Please select some text and try again.');
textRange.contents = myContents;
textRange.select(true);
var textFrame = getTextFrame(textRange);
if (textFrame)
textFrame.name = 'New Name';
})();
/**
* Returns the TextFrame containing the given textRange
* @author m1b
* @version 2024-10-15
* @param {TextRange} textRange - the target textRange.
* @returns {TextFrame?}
*/
function getTextFrame(textRange) {
var story = textRange.parent;
var textFrames = story.textFrames;
for (var i = 0, textFrame, frameText; i < textFrames.length; i++) {
textFrame = textFrames[i];
// get the TextRange of the current TextFrame
var frameText = textFrame.textRange;
// compare the character offset of the TextRange within the frame
if (
textRange.start >= frameText.start
&& textRange.end <= frameText.end
)
return textFrame;
};
};
Copy link to clipboard
Copied
@m1b Thank you once again. You and Bob are just like Doraemon.
Copy link to clipboard
Copied
😝 なんとかなるさ
Copy link to clipboard
Copied
There are very good text expander applications for both Mac and Windows OS (e.g. aText or Beeftext). Mac OS even has a built-in snippet tool.
Probably more convenient than a script.