Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intellij IDEA plugin development. Action "create kotlin class"

I want to create a plugin for Intellij IDEA. I need to add an action (AnAction) that will create a class in Kotlin (not Java) in a custom package. I have two questions:

  • How to create files with the desired extension?
  • Or how to create a file with Kotlin class(from some base class) in a custom package?
like image 214
Владимир Широков Avatar asked Dec 07 '16 14:12

Владимир Широков


2 Answers

One possible way to accomplish this is to use PsiFileFactory.createFileFromText() to create an in-memory Kotlin file and then to pass that file as a parameter to PsiDirectory.add() to save it to the filesystem.

like image 152
yole Avatar answered Nov 20 '22 13:11

yole


Although yole's answer is correct, I would like to see more details about mistery PsiDirectory class.

//get directory by VirtualFile
PsiDirectory directory = PsiManager.getInstance(project).findDirectory((getKotlinSourceDir(project))

Get kotlin source dir:

private VirtualFile getKotlinSourceDir(Project project) {
    return project.getBaseDir().findChild("src").findChild("main").findChild("kotlin");
}

And than you can create subdirectories:

//someDirectoryName it is simple name 
//(i.e if you post "com.some.package" - it does not create com/some/package folder)
PsiDirectory newDirectory = psiDirectory.createSubdirectory(someDirectoryName);
like image 30
Владимир Широков Avatar answered Nov 20 '22 12:11

Владимир Широков