How to fill filename for CreateFileFromTemplateDialog
已回答
How I can prefill filename for this dialog window?
package ru.meanmail.actions
import com.intellij.ide.actions.CreateFileFromTemplateAction
import com.intellij.ide.actions.CreateFileFromTemplateDialog
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.jetbrains.python.sdk.PythonSdkType
import ru.meanmail.AllIcons
import ru.meanmail.getSdk
class CreateRequirementsFileAction : CreateFileFromTemplateAction(
"requirements.txt",
"Create a new requirements.txt file",
AllIcons.FILE
), DumbAware {
// TODO: убирать сразу `pkg-resources==0.0.0`
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
builder.setTitle("Create a new requirements.txt file. Enter prefix").addKind(
"Blank Requirements file",
AllIcons.FILE,
"Blank Requirements File"
).addKind(
"Requirements with installed packages",
AllIcons.FILE,
"Freeze Requirements File"
)
}
override fun getActionName(
directory: PsiDirectory,
newName: String, templateName: String
): String {
return "Create A New Requirements File"
}
override fun isAvailable(dataContext: DataContext): Boolean {
val project = dataContext.getData("project") as? Project ?: return false
val sdk = getSdk(project)
return sdk?.sdkType is PythonSdkType
}
override fun hashCode(): Int = 0
override fun equals(other: Any?): Boolean = other is CreateRequirementsFileAction
override fun startInWriteAction() = false
override fun createFile(name: String?, templateName: String?, dir: PsiDirectory?): PsiFile? {
val template = FileTemplateManager.getInstance(dir!!.project).getInternalTemplate(templateName!!)
return createFileFromTemplate(name + "requirements.txt", template, dir)
}
}

请先登录再写评论。
Unfortunately current API doesn't support such feature as default text in "New Item" popup.
Should user be able to change this predefined name in your case?
If answer is "No", then you'd better use ListPopup instead of CreateWithTemplatesDialogPanel in this action (see com.intellij.openapi.ui.popup.JBPopupFactory#createListPopup method). In this case your popup should look like "New Scratch File" one.
But for this solution you cannot just extend CreateFileFromTemplateAction, so you will have to implement your own AnAction. This way is a bit longer
If the answer for the question above is "Yes" or you don't want to use ListPopup instead of CreateWithTemplatesDialogPanel then please vote for this issue in YouTrack.
Hope this helps.
I vote the issue. Thanks.