Is there an option to delete every comment enclosed within (* *)s for a whole notebook? Or is it possible to do it with some string processing?

  • 3
    $\begingroup$ Converting a cell to StandardForm eliminates comments in the cell. Select all Input cells in the notebook by option-clicking (on a Mac, I don't know the Windows keyboard equivalent) on the cell bracket of any Input cell, and use Cell > Convert To > StandardForm (shift-command-N) to remove comments in the whole notebook. Be aware that reformatting a cell will also eliminate any manual formatting, such as extra carriage returns you may have put in to improve readability of your code, so use with caution. $\endgroup$
    – Daniel W
    Commented Jul 29, 2019 at 2:27
  • $\begingroup$ Do you want to leave empty comments, or do you want to remove comments altogether? (The body seems to suggest the former and the title the latter.) $\endgroup$ Commented Jul 29, 2019 at 12:57
  • $\begingroup$ @Peter Mortensen To remove all comments including the (* *) pair, not leaving empty comments. Sorry for any confusion. $\endgroup$
    – nanjun
    Commented Jul 29, 2019 at 15:03
  • $\begingroup$ @Daniel W selecting the cells and converting to StandardForm is a great idea. Thank you. $\endgroup$
    – nanjun
    Commented Jul 29, 2019 at 20:52
  • $\begingroup$ @nanjun Kuba’s answer is a better long term solution, which is why I put my answer as a comment. That said, sometimes all you are looking for is a quick set of keystrokes, and I have always liked the “select all cells of this type” trick. $\endgroup$
    – Daniel W
    Commented Jul 31, 2019 at 23:39

1 Answer 1


String processing is not needed, fortunately because you'd have to detect nested string/comment patterns. It is easy with existing box structure though:

deleteComments[] := deleteComments @ EvaluationNotebook[]; 

deleteComments[nb_NotebookObject] := (
  SelectionMove[nb, All, Notebook]
; NotebookWrite[nb, DeleteCases[NotebookGet[nb], RowBox[{"(*", ___, "*)"}], Infinity]]

You can run deleteComments[] from your notebook or target any notebook you wish.

  • $\begingroup$ Is it possible to condense your two definitions into a single one using a default argument? $\endgroup$ Commented Jul 29, 2019 at 13:47
  • $\begingroup$ @AccidentalFourierTransform but then you'd have to have a HoldAll attribute to not evaluate EvaluationNotebook[] too early. Or some kind of Unevaluated shenanigans. So this is the way I write such functions. $\endgroup$
    – Kuba
    Commented Jul 29, 2019 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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