Idea Plugin dev - PSI File (Program Structure Interface - Tree Structured Content)
> Integrated development environment (ide) > IntelliJ - IDEA > Idea - Plugin Development
Table of Contents
1 - About
A PSI (Program Structure Interface) file is the root of a structure representing the contents of a file as a hierarchy of elements in a particular programming language.
It represents a hierarchy of PSI elements (so-called PSI trees).
A single PSI file may include several PSI trees in a particular programming language. A file may have multiple PSI file (if many language). A File View Providers manages this case ??
2 - Articles Related
3 - Management
3.1 - Interface / Creation
The PsiFile class is the common base class for all PSI files, while files in a specific language are usually represented by its subclasses.
For example:
- the PsiJavaFile class represents a Java file,
- and the XmlFile class represents an XML file.
As PSI is language-dependent, PSI files are created through the Language object, by using the LanguageParserDefinitions.INSTANCE.forLanguage(language).createFile(fileViewProvider)
method.
Like documents, PSI files are created on demand when the PSI is accessed for a particular file.
The PsiFileFactory.getInstance(project).createFileFromText()
method creates an in-memory PSI file with the specified contents.
To save the PSI file to disk, use the PsiDirectory.add() method.
3.2 - Scope
Scope: PSI has project scope (the same file is represented by multiple PsiFile instances if the file belongs to multiple projects open at the same time).
3.3 - Get
- From an action:
e.getData(LangDataKeys.PSI_FILE)
- From a VirtualFile:
PsiManager.getInstance(project).findFile()
- From a Document:
PsiDocumentManager.getInstance(project).getPsiFile()
- From an element inside the file:
psiElement.getContainingFile()
3.4 - View
3.5 - Find
To find files with a specific name anywhere in the project, use FilenameIndex.getFilesByName(project, name, scope)
3.6 - Operations
Most interesting modification operations are performed on the level of individual PSI elements, not files as a whole.
- To iterate over the elements in a file, use
psiFile.accept(new PsiRecursiveElementWalkingVisitor()…);
Any changes done to the content of PSI files are reflected in documents, so all rules for working with documents (read/write actions, commands, read-only status handling) are in effect.
3.7 - Persistence
Like documents, PSI files are weakly referenced from the corresponding VirtualFile instances and can be garbage-collected if not referenced by anyone.
3.8 - Watcher / Notification
PsiManager.getInstance(project).addPsiTreeChangeListener()
allows you to receive notifications about all changes to the PSI tree of a project.
3.9 - How do I extend PSI to support additional languages
PSI can be extended to support additional languages through custom language plugins: IDEA Plugin Dev - Custom Language Plugin