Run live template programmatically in another file (and replace variable)


use-case is following: I have XML file and being on certain XML attribute I want to generate function (live template) in script file named according to that XML attribute. So far I have code

public void actionPerformed(AnActionEvent e) {
if (e == null) {
final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
final Document document = editor.getDocument();

PsiFile psiFile = PsiDocumentManager.getInstance(e.getProject()).getPsiFile(document);
int caret = editor.getCaretModel().getOffset();
PsiElement element = PsiTreeUtil.getParentOfType(psiFile.findElementAt(caret), XmlAttributeValue.class);

String vslFileName = getValueFromElement(element, 0);
String vsfFunctionName = getValueFromElement(element, 1);
PsiFile vslFile = getVslFile(vslFileName, e.getProject());
if (StringUtils.isNotEmpty(vslFileName) && vslFile != null) {
int lineCount = countLines(vslFile.getText());
OpenFileDescriptor openFileDesc = new OpenFileDescriptor(e.getProject(), vslFile.getVirtualFile(), lineCount + 2, 0);
Editor vslEditor = FileEditorManager.getInstance(e.getProject()).openTextEditor(openFileDesc, true);
Template vslTemplate = TemplateSettings.getInstance().getTemplate("func", "VSL");

if (vslEditor != null && vslTemplate != null) {
TemplateManager.getInstance(e.getProject()).startTemplate(vslEditor, vslTemplate);


It's basically working but there are 2 major issues:

1) It won't add generated code from live template at the end of file if last row is "}". There has to be also empty row after, otherwise is breaks previous function.

2) I want to have pre-filled function name so basically replace $FUNCNAME$ in code. I can do that for FileTemplate because there is setText() method but not for Template.


Thank you very much.






1) As soon as you have an editor, you free to add any modification in document, including adding new line at the end of the file and putting caret just before it.

2) There is a com.intellij.codeInsight.template.TemplateManager#startTemplate method that accepts map of predefined variables.


2) Obviously I overlooked it, thx.

1) Not so easy, Document#setText method is complaining on read-only mode. Has to be modified in separate thread? Please would you like to post some example code how to safely add new lines  - related my code.


Please provide full output. If the document is really in read-only mode, you won't be able to run live template on it as well.


Btw, I'd rather use insertString/replaceString method or EditorModificationUtil instead of setText.


Oh...I was wrong about exception, it's:

Assertion failed: Write access is allowed inside write-action only (see com.intellij.openapi.application.Application.runWriteAction())
at com.intellij.openapi.diagnostic.Logger.assertTrue(
at com.intellij.openapi.application.impl.ApplicationImpl.assertWriteAccessAllowed(
at com.intellij.openapi.editor.impl.DocumentImpl.assertWriteAccess(
at com.intellij.openapi.editor.impl.DocumentImpl.replaceString(
at com.intellij.openapi.editor.impl.DocumentImpl.lambda$setText$3(
at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(
at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(
at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(
at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(
at com.intellij.openapi.editor.impl.DocumentImpl.setText(
at com.vendavo.plugin.actions.GenerateVslFunction.actionPerformed(
at com.intellij.openapi.actionSystem.ex.ActionUtil$
at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(
at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.performAction(
at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.performAction(
at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.lambda$onChosen$0(
at com.intellij.openapi.application.TransactionGuardImpl.performUserActivity(
at com.intellij.ui.popup.AbstractPopup.lambda$null$7(
at java.awt.event.InvocationEvent.dispatch(
at java.awt.EventQueue.dispatchEventImpl(
at java.awt.EventQueue.access$500(
at java.awt.EventQueue$
at java.awt.EventQueue$
at Method)
at java.awt.EventQueue.dispatchEvent(
at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(
at com.intellij.ide.IdeEventQueue._dispatchEvent(
at com.intellij.ide.IdeEventQueue.dispatchEvent(
at java.awt.EventDispatchThread.pumpOneEventForFilters(
at java.awt.EventDispatchThread.pumpEventsForFilter(
at java.awt.EventDispatchThread.pumpEventsForHierarchy(
at java.awt.EventDispatchThread.pumpEvents(
at java.awt.EventDispatchThread.pumpEvents(


I will try EditorModificationUtil way.


Well, the exception says what you should to do: wrap document modification with com.intellij.openapi.application.Application.runWriteAction().

Also CommandProcessor.getInstance.executeCommand would be useful in future, just read exception messages carefully ;)


Ouch, very lame. So final code might be:

e.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> {
try {
EditorModificationUtil.insertStringAtCaret(vslEditor, " \\\n\\\n");
catch (Exception ex) {
"Add new lines at the end of vsl script file",

Only issue is how to insert new lines, I tried "\r\n", separate, does not work correctly - it removes last character of editor "}" and there is one backslash extra :(



> Only issue is how to insert new lines

"\n" is the new line. "\r" should not be used.

Btw, using WriteAction#runWriteCommandAction might be more handy. 


Please sign in to leave a comment.