4
$\begingroup$

This is a generalization of this question, which already has very nice answers.

Suppose str is a string of valid code, so that ToExpression[str] generates an output. I can copy/paste the contents of str into a cell and then evaluate this cell manually.

But I'd like to automate the process of generating an input cell containing the contents of str. That is, I'm looking for a function makeCell[str_] that generates an input cell with the contents of str. This seems doable because it can be done by copy/pasting, and functions like ToExpression and CellPrint exist (see above post and this one for specific examples). But so far I haven't found a solution.

Is this possible?

$\endgroup$

1 Answer 1

5
$\begingroup$

TLDR: FrontEnd will happily accept an input form string wrapped with BoxData:

NotebookWrite[
  EvaluationNotebook[]
, BoxData @ "Module[{x}, x = 1]"
]

Incorporate it in methods you use from previous questions.

Btw, in case it didn't accept strings:

NotebookWrite[
  EvaluationNotebook[]
, ToExpression["Module[{x}, x = 1]", InputForm, MakeBoxes]
]
$\endgroup$
6
  • $\begingroup$ Nice. This is so simple, I feel it's really the "right" answer to my linked question as well. $\endgroup$
    – WillG
    Commented Jul 21, 2022 at 6:11
  • $\begingroup$ To make the generated cell also be an initialization cell, you can use CellPrint[ Cell[BoxData@"Module[{x}, x = 1]", "Input", InitializationCell -> True]]. I can't find a way to do this using NotebookWrite, and some people in the linked post warn against using CellPrint for various reasons, but it works fine for me. $\endgroup$
    – WillG
    Commented Jul 21, 2022 at 19:38
  • 1
    $\begingroup$ @WillG NotebookWrite[Evaluation Notebook[] , Cell[... , "Input", InitializationCell->True]] ? $\endgroup$
    – Kuba
    Commented Jul 21, 2022 at 19:43
  • $\begingroup$ Whoops, forgot those options went into Cell and not CellPrint. Thanks! $\endgroup$
    – WillG
    Commented Jul 21, 2022 at 19:48
  • $\begingroup$ For strings containing new lines I ran into an error for MakeBoxes not having the right number of arguments. I could fix it by removing the new lines but this comes at the cost of not having new lines in the produced cell and having to add them back in by hand. How would I make this robust for strings containing newlines (and multiple lines of code separated by ;). $\endgroup$
    – Kvothe
    Commented Mar 6, 2023 at 13:32

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.