@NotNull public static Editor getInjectedEditorForInjectedFile( @NotNull Editor hostEditor, @Nullable final PsiFile injectedFile) { if (injectedFile == null || hostEditor instanceof EditorWindow || hostEditor.isDisposed()) return hostEditor; Project project = hostEditor.getProject(); if (project == null) project = injectedFile.getProject(); Document document = PsiDocumentManager.getInstance(project).getDocument(injectedFile); if (!(document instanceof DocumentWindowImpl)) return hostEditor; DocumentWindowImpl documentWindow = (DocumentWindowImpl) document; SelectionModel selectionModel = hostEditor.getSelectionModel(); if (selectionModel.hasSelection()) { int selstart = selectionModel.getSelectionStart(); int selend = selectionModel.getSelectionEnd(); if (!documentWindow.containsRange(selstart, selend)) { // selection spreads out the injected editor range return hostEditor; } } if (!documentWindow.isValid()) return hostEditor; // since the moment we got hold of injectedFile and this moment call, // document may have been dirtied return EditorWindow.create(documentWindow, (EditorImpl) hostEditor, injectedFile); }