Split PSI file to PSI elements chunks

Answered

Hello.

I'm creating my first IntelliJ plugin and I want to get a file content in PSI format so I can read data from it.
The file I'm trying to read is .yml and look something like this:

 

functions:
addTodo:
handler: src/addTodo.handler
events:
- httpApi:
path: /
method: post
fetchTodos:
handler: src/fetchTodos.handler
events:
- httpApi:
path: /todos
method: get
fetcTodo:
handler: src/fetchTodo.handler
events:
- httpApi:
path: /todo/{id}
method: get
updateTodo:
handler: src/updateTodo.handler
events:
- httpApi:
path: /todo/{id}
method: put

 

I would like to get all functions names and know their row number. So far I was only able to get the all files as text using the PsiManager.

PsiManager.getInstance(project).findFile(file);

 

How can I get the function names and row number?

0
1 comment

Hi Gili,

  1. You can find all YAML files using com.intellij.psi.search.FileTypeIndex.getFiles().
  2. Then you can use the snippet you pasted to get PsiFilePsiManager.getProject(project).findFile(virtualFile).
  3. Once you have the PsiFile, you can iterate over its children PSI elements (PsiFile is the root in the file PSI structure) using com.intellij.psi.util.PsiTreeUtil.
  4. To understand how the tree is built, you can use PsiViewer. More information here: https://plugins.jetbrains.com/docs/intellij/explore-api.html#31-use-internal-mode-and-psiviewer
  5. When you have PSI elements reflecting function names, you can get names with PsiElement.getText().
  6. To get a line number, you can use Document.getLineNumber(textOffset) method.
0

Please sign in to leave a comment.