Most things that can be done via the front-end interface in Mathematica can also be accomplished by some function. Is that the case for find-and-replacing? That is, is there some code I could execute in a Mathematica notebook that would have the same effect as me using the Edit > Find… window to replace all occurrences of "find this text"
with "replace with this text"
through the whole notebook?
-
$\begingroup$ Related: (27001) $\endgroup$ – Mr.Wizard May 15 '15 at 6:44
Update: I think I've got it.
I found a token that does the replacement without bringing up a dialog. The values from the last use of the Find and Replace dialog will be used. The command is:
FrontEndExecute @ FrontEndToken[nb, "ReplaceAll"]
where nb
is the target Notebook object.
To preset the Find and Replace fields one can modify the FindSettings
option of the Front End like so:
CurrentValue[$FrontEnd, {FindSettings, "FindString"}] = "This";
CurrentValue[$FrontEnd, {FindSettings, "ReplaceBoxes"}] = "That";
Now:
FrontEndExecute @ FrontEndToken[nb, "ReplaceAll"]
After:
Version 7
In version 7 under Windows I need this variation for the method to work:
CurrentValue[$FrontEnd, {FindSettings, "ReplaceString"}] = "That";
-
$\begingroup$ I can't make functions from
SystemResources/Find.nb
working, any idea?FE`Evaluate[ FEPrivate`FindExpression[ FrontEnd`CurrentValue[ FrontEnd`$FrontEnd, {FindSettings, "FindBoxes"}], "Previous", False, False, False]]
$\endgroup$ – Kuba♦ May 15 '15 at 7:32 -
$\begingroup$ @Mr.Wizard The
"FindString"
option seems to work as expected for me, but the"ReplaceBoxes"
(or"ReplaceString"
, which I also tried) option has no effect. (Mma 9.0.1.0) $\endgroup$ – thecommexokid May 15 '15 at 16:46 -
$\begingroup$ @thecommexokid Possibly just the
CurrentValue
method is failing. Please use the Find and Replace dialog with unique values for the find and replace fields, then evaluateOptions[$FrontEnd, FindSettings]
and tell me if the suboptions"FindString"
and"ReplaceBoxes"
exist, and have been set to the values you entered. If so it should be possible to get this working. $\endgroup$ – Mr.Wizard May 16 '15 at 3:20 -
$\begingroup$ Yes,
Options[$FrontEnd, FindSettings]
gives the values I entered. $\endgroup$ – thecommexokid May 18 '15 at 1:20 -
$\begingroup$ And
CurrentValue[$FrontEnd, {FindSettings, "ReplaceBoxes"}] = "differentString"
returnsNull
, but if I executeOptions[$FrontEnd, FindSettings]
again afterward, theReplaceBoxes
setting shows the new value. $\endgroup$ – thecommexokid May 18 '15 at 1:21