3

How to delete all the cells below the cursor? I want to remove all the cells that are used for experimenting with various function arguments which are typically at the bottom of the notebook.

How do power users typically cleanup code?

Talespin_Kit
  • 164
  • 5

2 Answers2

7

1. Second Notebook

Use a second empty notebook to test your code.

2. Grouped Cells

Use titles to automatically create a group of cells, which can then easily be selected and deleted.

enter image description here

3. NotebookDelete[]

NotebookDelete[Cells[][[First@FirstPosition[Cells[], EvaluationCell[]] ;;]]]

enter image description here

Domen
  • 23,608
  • 1
  • 27
  • 45
1

The following code will create a button. Pressing the button will delete all cell groups below the cell group where the cursor is:

clean[] := Module[{i = 0},
  nb = SelectedNotebook[];
  SelectionMove[nb, Above, CellGroup];
  NotebookDelete[nb];
  While[NextCell[] =!= None, If[i++ > 10, Break[]];
    NotebookDelete[nb];
    SelectionMove[nb, Next, CellGroup];]
  ]
  Button["Clean", clean[]
]
MarcoB
  • 67,153
  • 18
  • 91
  • 189
Daniel Huber
  • 51,463
  • 1
  • 23
  • 57
  • This solution leaves the evaluated clean function in the notebook. That needs to be manually removed. – Talespin_Kit Jan 22 '22 at 20:44
  • The OP states "delete all the cells BELOW the cursor" – Daniel Huber Jan 23 '22 at 09:17
  • After evaluating the "clean" method which creates the button and then moving the cursor above the evaluated cell and clicking "clean" button does not clear the cells below the cursor(ie. the evaluated clean method and its output button). I am new to Mathematica and I am not aware of "Module" and most of the functions used in the "clean" method. Is my usage of the "clean" correct? – Talespin_Kit Jan 23 '22 at 18:47
  • If you move the curser to a cell group above the cell with "clean" and "Button", then this will be erased, including the created button, – Daniel Huber Jan 23 '22 at 19:04