How do you extract selected text in MATLAB?

MATLAB has several selection-sensitive parameters. For example, if you select text and press F9, it will evaluate your choice. (If you have not changed your keyboard settings.)

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

But what is included in GetSelection?

+5
source share
3 answers

Thanks to @Yair Altman's undocumented Matlab , I managed out of java commands to do this work.

Put this in the shortcut (or the function 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)
+5

, - Matlab, Mathworks API ( , Google). , , .m (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/brxijcd.html). UIcontrol , , , .

0

- , , , .

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

Finally, I created a shortcut with this code in the upper right corner of Matlab, which I quickly access 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
0
source

All Articles