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


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/ 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?

Comment actions Permalink

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.

Comment actions Permalink

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

Comment actions Permalink

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.

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

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

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

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.

Comment actions Permalink

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.


Please sign in to leave a comment.