Get selectText 、selectStartPosition、selectEndPosition、fileName from diff window right-click menu

Answered

Hello team

I 'm developing a plugin work with git and add a action to diff window right-click menu by code blew:

<action popup="true" id="action1",class="demo.action.Action1">
	<add-to-group group-id="Diff.EditorPopupMenu" anchor="last"/>
</action>

And here is the Action1code:

public class Action1 extends AnAction{
	public Action1 (){
		super("add");
	}
	
	@Override
	public void actionPerformed(@NotNull AnActionEvent e){
		//I want to get selectText、selectStartPosition、selectEndPosition、fileName here if user select text from the diff window
	}
}

So how to get them?

0
6 comments

Hi,

Try:

Editor editor = e.getData(CommonDataKeys.EDITOR);
SelectionModel selectionModel = editor.getSelectionModel();

to get the editor and its selection model and call its methods.

0

Thanks,I can get selectText、selectStartPosition、selectEndPosition from the SelectionModel  but I cannot find the fileName 

 Where can I get it?

0

Thanks,I get all I need from code blew:

public viod actionPerformed(@NotNull AnActionEvent e){
    var editor = e.getData(CommonDataKeys.EDITOR);
    var currentFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    
    var selectionModel = editor.getSelectionModel();
    var startLine = selectionModel.getSelectionStartPosition().getLine();
    var endLine = selectionModel.getSelectionEndPosition().getLine();
    var selectText = selectionModel.getSelectedText();
    String fileName = Paths.get(project.getBasePath()).relativize(Path.get(currentFile.getPath())).toString();
}


Be careful, I omitted all  null checks.

 

0

I don't understand the fileName logic. currentFile.getName() is enough. Avoid using project.getBasePath() (see its Javadoc).

0

you are right. In fact I make a mistake. 

Code:

Paths.get(project.getBasePath()).relativize(Path.get(currentFile.getPath())).toString()

is the way which I use to get file relative path ,not the fileName.

 

0

Please sign in to leave a comment.