Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you retrieve the selected text in MATLAB?

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?

like image 315
Richie Cotton Avatar asked Aug 20 '10 16:08

Richie Cotton


1 Answers

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)
like image 150
Jonas Avatar answered Oct 22 '22 17:10

Jonas