How do you retrieve the selected text in MATLAB?

2020-03-03 08:03发布

问题:

MATLAB has several selection-sensitive capabilities. For example, if you select some text and press F9, it evaluates your selection. (Unless you've remapped your keyboard settings.)

I'd like to be able to replicate this functionality with for a shortcut. So, for example, I want to click a shortcut that displays the current selection. My shortcut callback would be disp(GetSelection()).

But what goes into GetSelection?

回答1:

Thanks to @Yair Altman's undocumented Matlab, I was able to figure out the java commands to make this work.

Put this in a shortcut (or a function that is called by the shortcut):

%# find the text area in the command window
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
try
  cmdWin = jDesktop.getClient('Command Window');
  jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0);
catch
  commandwindow;
  jTextArea = jDesktop.getMainFrame.getFocusOwner;
end

%# read the current selection
jTxt = jTextArea.getSelectedText;

%# turn into Matlab text
currentSelection = jTxt.toCharArray'; %'

%# display
disp(currentSelection)


回答2:

I don't believe there is any way to control or read the selection from the Matlab text editor, there is no mention of such an API on the Mathworks website (at least from a quick search on Google). If you want this functionality to enable more advanced text editing, then you might want to consider setting the .m file editor to an external editor (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brxijcd.html). It may be possible to read the selection from a UIcontrol in a custom GUI, but I don't think this is what you want.



回答3:

In case you want to use something like this but with text highlighted in the editor rather than in the command window.

I use the following code in order to be able to quickly check the nnz() of a variable, although you can change the code in the nested try-catch to whatever you need.

Lastly, I created a shortcut with this code in the top right of Matlab, which I access quickly by pressing Alt-1.

try
    activeEditor = matlab.desktop.editor.getActive;
    currentSelection = activeEditor.SelectedText;

    try
        eval(sprintf('val = nnz(%s);',currentSelection))
        disp(sprintf('>> nnz(%s) = %s',currentSelection,num2str(val)))
    catch ex
        disp(ex.message)
    end
catch ex
    disp(ex.message)
end