views:

65

answers:

2

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?

A: 

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.

Patrick Mineault
+3  A: 

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)
Jonas
@Jonas: This is very cool. Thanks.
Richie Cotton

related questions