How do I open a file if I have the path to it in the project?

Hello!

I am new to plugin development for IntelliJ. I would like to make a simple plugin for learning purpose where I can open a file in a project. Let´s say the path to the file is project/src/mypackage/myfile.java. How can I open that file with code (like if I opened it with Ctrl+Shift+N)?

I have looked at VirtualFile and it seems that is the IDEA`s representation of the physical file on the IDEA Virtual File System, right?

Do I have to use FileDocumentManager in some way?

0

See com.intellij.ide.actions.GotoFileItemProvider#filterElements how to determine PsiFileSystemItem from given path. Then simply call com.intellij.pom.Navigatable#navigate to open editor.

0

To get VirtualFile by path use LocalFileSystem.getInstance().findFileByPath(). Or see this doc.
Then call FileEditorManager.getInstance(project).openFile(file, true);

0
Avatar
Permanently deleted user

Thanks for linking to a very good FAQ! I solved the question stated in the topic.
Another question, how do I get the line number on witch the mouse pointer is at on a document?  I have tried with the below code, but it does not quiet work.

   @Override
    public void update(AnActionEvent e) {
        Editor editor = e.getData(LangDataKeys.EDITOR);
        if editor == null) {
            return;
        }

        int offset = editor.getCaretModel().getVisualLineStart(); // Does not get the correct line number

        System.out.println("Caret offset = "+offset);
    }


EDIT:
I succeeded to get the line number with the following code:

int lineNumber = editor.getDocument().getLineNumber(editor.getCaretModel().getOffset()) + 1;


1) Is this the correct way to get the line number, or is there an even better way?
2) How do I SET the line number? I can only see a getLineNumber() method, not a setLineNumber() method.

0

I wouldn't expect getVisualLineStart() and getVisualLineEnd() to return current line especially after reading its docs.
Document.getLineNumber() is ok. CaretModel.getLogicalPosition() should work as well.
CaretModel has several moveXXX() methods to set caret position. See javadocs and see other usages in Community Edition source code.

0

Can someone point me to the right resource which has the detailed explanation as how to open a file in editor programmatically

0

Ramyaram2092 please do not 7 years old thread, please start new thread and provide more details on what data you have about "a file" and what you want to achieve

0

请先登录再写评论。