Editor for partial file?

I'm trying to make a small multi-line editor for a portion of a code file.  That is, given a file like:

package MyPackage;

import java.util.Random;

public class MyClass {

    private int param;
    private final Random random = new Random();

    public MyClass(int param) {
        this.param = param;
    }

    public double multiplyByRandom() {
        int paramTimesTwo = param * 2;
        return param * random.nextDouble();
    }
}


I'd like to pop up an Editor that just shows the contents of a code block:

return param * random.nextDouble();


I can make an editor that contains the .getText() of the appropriate PsiElement.  But ideally, it would be just like you were directly editing the source file - same syntax highlighting, code completion, and sync back changes to the original file.  Any ideas how to do that?  I've been looking for inspiration in DocumentWindow and DebuggerStatementEditor code, but haven't figured out how to make it work yet.

Thanks!

-Eric

0
3 comments
Avatar
Permanently deleted user

Hi Eric,

You can use EditorTextField.

There's a constructor:

new EditorTextField(Document document, Project project, FileType fileType)


Here's one way to get a document (method is PsiMethod that you wan't to change, psiClass is PsiClass of your class):

        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();

        PsiCodeFragment fragment = factory.createExpressionCodeFragment(method.getBody().getText(), method.getBody(), factory.createType(psiClass), true);



        PsiDocumentManager dm = PsiDocumentManager.getInstance(project);
        Document doc = dm.getDocument(fragment);


File type can be created this way:
        FileTypeManager.getInstance().getFileTypeByExtension("java")



Hope this helps,
Tomas
0

OK, my EditorTextField from last year is working fine (thanks for the help!).  But now I have a more difficult problem.  I'd really like to make an EditorTextField where the user is already in the context of a single parameter to a method - so you can type Ctrl-P to see parameter info, and it shows an error if your code doesn't evaluate to the correct type.

For instance, I have "void something(String param) {}" in my context.  The best option I know of now is to populate an EditorTextField with "something()" and put the caret between the ()s.  But I'd like to hide that surrounding text entirely if it's possible.  Is that possible?

Thanks.

0

This is controlled through the 'context' argument of createExpressionCodeFragment(). I'm not sure if the specific scenario that you want to implement is achievable, but you can give it a try.

0

Please sign in to leave a comment.