Detecting if a front end token is available to execute
Asked Answered
S

1

9

How can I detect if a front end token is available to execute? Alternately, how can I detect if a front end token failed to execute?

Example: the Edit -> Copy command is not available if nothing is selected. FrontEndTokenExecute["Copy"] will simply beep in this case, but it gives me no (programmatic) indication that it has failed.

Stouthearted answered 1/1, 2012 at 18:53 Comment(2)
Your question made me wonder if I could find an undocumented Q function, so I evaluated ?**Q and found NotebookToolsCellsSelectedQ. (I have not tried using it; dunno exactly how this is supposed to be evaluated.) Also see my comment on Sjoerd's answer regarding hiding the message window. Finally, you might also hunt through ?FrontEnd** and ?FrontEnd*`*Q* for more ideas.Neologism
@Neologism Interesting find! There seem to be several useful functions in NotebookTools` . I can't use this because it only returns True if full cells are selected (not just text in the cells), but looking at the source is already good inspiration. Perhaps I can come up with something more efficient than NotebookRead@SelectedNotebook[].Stouthearted
B
5

I found a method to deal with your second question, but it's not elegant:

  1. In Preferences > Interface > Message and Warning actions set Minor user interface warnings to Beep and Print to Console
  2. Make sure there is at least one error message in the message window
  3. Obtain a handle to the message window notebook (using Notebooks[] or so)
  4. Store the last cell in the message notebook using NotebookGet[NotebookObject[FrontEndObject[LinkObject["55d_shm", 1, 1]], 1]]/. Notebook[{___, Cell[a___]}, ___] :> Cell[a] (your handle will look differently, of course)
  5. Your call: FrontEndTokenExecute["Copy"]
  6. Get the last error message and check whether it differs from the one stored in step 4.
  7. The error cell looks like Cell["You tried to edit a cell that is not editable. You can make the \ cell editable by choosing Cell Editable in the Cell Properties \ submenu.", "Message", "Message", "MSG", PageWidth -> WindowWidth, ShowCellLabel -> True, CellChangeTimes -> {3.534442831*10^9}, CellTags -> "cantEditLockedCell"]
  8. Act appropriately
Bans answered 1/1, 2012 at 22:3 Comment(2)
Interesting hack. Suggestion: Couldn't you also set the message window to be hidden? Not sure if this is possible or not. (i.e., global properties may not allow it.)Neologism
Thanks Sjoerd! I was looking for a solution that will just work on any system without additional setup, so finally I gave up on this, and I tried NotebookRead@SelectedNotebook[] to just test if there is a selection. The drawback of this method is that it is possible that the selection contains a huge amount of data, and it might be slow to retrieve (e.g. when too much output is generated and Mathematica wraps it in that "show more/less" box)Stouthearted

© 2022 - 2024 — McMap. All rights reserved.