2
$\begingroup$

When I develop a package I typically open a new notebook and start writing functions which I need until I have a version which I am happy with. Then I copy them to a m-file. During this process I usually go back to an existing cell and change few things and hit SHIFT+RETURN to see the effect of changes. The problem is that as the this happens during several sessions, when I go through the cells in a notebook, the order of the cells does not necessarily represent the order in which I have carried out the calculations.

I was wondering if it is possible to have a shortcut such that every time I want to reevaluate an existing cell, it gets copied to the end of notebook. Preferably the shortcut should have two version such that one just copies the cell to the end of notebook (just in case I want to make some changes before evaluating it) and the other copies the cell to the end of notebook and evaluates it without any changes. Of course I can do this manually for each cell but it would be nice to have a less time consuming way to do this.

$\endgroup$
1
$\begingroup$

Rather than adding a cell at the bottom of the InputNotebook after every evaluation, the following function takes the input and output cells for a given range of line numbers, and writes them in evaluation order in a new Notebook:

Options[evaluationSequenceNB]={"IncludeOutput"->True};

evaluationSequenceNB[opts:OptionsPattern[]] := evaluationSequenceNB[1;;$Line, opts]
	evaluationSequenceNB[s_Span, opts:OptionsPattern[]] := evaluationSequenceNB[Range[$Line][[s]], opts]
evaluationSequenceNB[rng_, OptionsPattern[]] := Module[{cells},
    cells = toInCell[InString[rng], rng];
    If[TrueQ@OptionValue["IncludeOutput"],
        cells=Riffle[
            cells,
            Replace[
                DownValues[Out][[rng]],
                _[_[_[line_]], z_] :>toOutCell[MakeBoxes[z], line],
                {1}
            ]
        ]
    ];
    NotebookPut[Notebook[cells]]
]

SetAttributes[toInCell, Listable];
toInCell[boxString_, line_] := Cell[
    ToExpression[boxString, StandardForm, BoxData],
    "Input",
    CellLabel->"In["<>ToString[line]<>"]:="
]

toOutCell[boxes_, line_] := Block[{$Line=line},
    Cell[
        BoxData @ ToBoxes @ OutputSizeLimit`PrePrint[RawBoxes@boxes],
        "Output",
        CellLabel->"Out["<>ToString[line]<>"]="
    ]
]

For example, here is an image of a notebook after evaluating 3 inputs, where the order is reversed (as you can see by the In/Out numbers):

enter image description here

And, here is the notebook generated by evaluationSequenceNB:

enter image description here

$\endgroup$

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.