如何以编程方式在MATLAB编辑器中执行“collapse-all-folds”?

我一直在努力解决这个问题的时间比我想承认的要长一些。

我正在尝试以编程方式执行当用户单击“ View > Collapse All按钮或在编辑器窗口中单击鼠标右键,然后单击Code Folding >“ Fold All Code Folding Action时发生的相同Action

到目前为止我发现了什么?

  • 可以在enum com.mathworks.mde.editor.ActionID找到与Action对应的String ,它是: 'collapse-all-folds'
  • Action激活时,似乎执行以下方法: org.netbeans.api.editor.fold.FoldUtilities.collapseAll(...) (因此netbeans标记)。
  • 这段代码允许我获取EditorActionActionManagerMatlabEditor实例:

 jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor; jAm = com.mathworks.mde.editor.ActionManager(jEd); jAc = com.mathworks.mde.editor.EditorAction('collapse-all-folds'); 

我的问题是我找不到实际激活 Action

任何想法/替代品?


EDIT1 :在“书”中挖了一下之后,我觉得我比以前更接近(但仍然不是那里)。 从书中引用:

Java GUI组件通常使用ActionMap来存储由侦听器在鼠标,键盘,属性或容器事件上调用的可运行Actions 与对象方法不同,MATLAB不能直接调用Actions

然后解释了一个解决方法,其中大致涉及:获取某种Action对象; 创建一个ActionEvent并使用ActionEvent作为参数调用ActionactionPerformed ,如下所示:

 import java.awt.event.*; jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor; jAm = com.mathworks.mde.editor.ActionManager(jEd); jAc = jAm.getAction(com.mathworks.mde.editor.EditorAction('collapse-all-folds')); jAe = ActionEvent(jAm, ActionEvent.ACTION_PERFORMED, ''); jAc.actionPerformed(jAe); 

这段代码运行没有错误 – 但是(似乎?)没有。 我怀疑我在错误的对象上调用ActionEventactionPerformedActionManager可能与此问题无关)。


PS

我知道有一个热键执行此操作( Ctrl + = ),但这不是我正在寻找的(除非有一个命令来模拟热键按:))。

经过不可估量的挖掘,试验和方式太多错误 – 我已经完成了!

 function FullyCollapseCurrentScript() %// Get the relevant javax.swing.text.JTextComponent: jTc = com.mathworks.mlservices.MLEditorServices ... .getEditorApplication.getActiveEditor.getTextComponent(); %// Get the FoldHierarchy for the JTextComponent: jFh = org.netbeans.api.editor.fold.FoldHierarchy.get(jTc); %// Finally, collapse every possible fold: org.netbeans.api.editor.fold.FoldUtilities.collapseAll(jFh); end 

或者如果被压缩成一个单一的,凌乱的命令:

 org.netbeans.api.editor.fold.FoldUtilities.collapseAll(... org.netbeans.api.editor.fold.FoldHierarchy.get(com.mathworks. ... mlservices.MLEditorServices.getEditorApplication.getActiveEditor. ... getTextComponent())); 

请注意,这适用于当前在编辑器中打开的脚本。

不是一个完美的解决方案,但可以使用java.awt.robot模拟默认热键按下。

…找到一种直接实际触发Action的方法会更好……

 import java.awt.Robot; import java.awt.event.*; RoboKey = Robot; jTextComp = com.mathworks.mlservices.MLEditorServices. ... getEditorApplication.getActiveEditor.getTextComponent; jTextComp.grabFocus() drawnow; %// give time for focus if jTextComp.hasFocus() RoboKey.keyPress(KeyEvent.VK_CONTROL); RoboKey.keyPress(KeyEvent.VK_EQUALS); RoboKey.keyRelease(KeyEvent.VK_CONTROL); RoboKey.keyRelease(KeyEvent.VK_EQUALS); com.mathworks.mde.cmdwin.CmdWin.getInstance.grabFocus; %// focus back to cmdwin else warning('Failed to collapse folds: Editor could not take focus') end