How do you retrieve the selected text in MATLAB?

前端 未结 3 1231
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 23:07

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

相关标签:
3条回答
  • 2021-01-05 23:42

    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)
    
    0 讨论(0)
  • 2021-01-05 23:50

    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
    
    0 讨论(0)
  • 2021-01-05 23:59

    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.

    0 讨论(0)
提交回复
热议问题