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?


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";


enter image description here

FrontEndExecute @ FrontEndToken[nb, "ReplaceAll"]


enter image description here

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 $\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 evaluate Options[$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" returns Null, but if I execute Options[$FrontEnd, FindSettings] again afterward, the ReplaceBoxes setting shows the new value. $\endgroup$ – thecommexokid May 18 '15 at 1:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.