Write in existing file after an action performed

Hi,

I would like to know how to write in existing file after an action.

When I do my action, I create some files and I need to add that file to a PHP config array in other file in the projects.

Can you give me some lead to do that?

9 comments
Comment actions Permalink

At least, You can just  do it with java File api.

Or when you get the psiFile, you can get it's document  than write to the document

0
Comment actions Permalink

I'm wondering how to do that when I get the psiFile. I need to add the new line, see my example:

<?php

namespace Intranet;

return [
'factories' => [

// Query
Model\Application\Query\Application\BuildCreateApplicationForm::class => Model\Application\Query\Application\BuildCreateApplicationFormFactory::class,
Model\Application\Query\Application\BuildEditApplicationForm::class => Model\Application\Query\Application\BuildEditApplicationFormFactory::class,
// Add new line here

]
];
0
Comment actions Permalink

Your question is unclear. What do you need help with? Writing a file? Invoking something after action? Why not do this in the action?

0
Comment actions Permalink

I need to write in the file which already exists and contains a PHP array.

0
Comment actions Permalink

You need to get a PsiFile of the file you need to modify, find an array in it and modify it. You may do this as a text modification (see com.intellij.openapi.editor.Document#insertString and friends) or as psi tree modification (see com.intellij.psi.PsiElement#add and friends)  . 

 

 

0
Comment actions Permalink

Can you provite some example?

I don't know how to add a psielement to a psifile or insertString from document.

Currently I have this:

VirtualFile configFile = project.getBaseDir().findFileByRelativePath("modules/config.php");
PsiFile file = PsiManager.getInstance(project).findFile(configFile);

PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
Document document = documentManager.getDocument(file);
document.insertString(offset, CharSequence);

But I don't know how to find an array in a psifile and how to know the offset to add the string or how to add a psielement to a psifile.

I think add a psielement is a better option but I don't know.

Thanks.

0
Comment actions Permalink

See  PsiTreeUtil.

 

0
Comment actions Permalink

Thank you but could you provide more example please?

There is a cookbook or something like that to know thing about Psi because the docs is small for that huge part :/

0
Comment actions Permalink

I guess only docs and IDEA community sources. Also, OSS plugins.

Here is example of converting foreach to for in my perl plugin: https://github.com/Camelcade/Perl5-IDEA/blob/master/core/src/com/perl5/lang/perl/idea/intentions/ForeachToForIntention.java

0

Please sign in to leave a comment.