3
$\begingroup$

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?

$\endgroup$

2 Answers 2

7
$\begingroup$

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

$\endgroup$
2
  • $\begingroup$ The second solution is great. Creating title with the keyboard shortcut "Alt + 1" and then using the mouse to select the cell and delete. Is there a way to delete the current cell without using the mouse? $\endgroup$ Jan 22 at 20:51
  • 1
    $\begingroup$ You can use CTRL + . to expand your selection, and then press Delete. However, you can also define your own keyboard shortcut. $\endgroup$
    – Domen
    Jan 22 at 21:15
1
$\begingroup$

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[]
]
$\endgroup$
4
  • $\begingroup$ This solution leaves the evaluated clean function in the notebook. That needs to be manually removed. $\endgroup$ Jan 22 at 20:44
  • $\begingroup$ The OP states "delete all the cells BELOW the cursor" $\endgroup$ Jan 23 at 9:17
  • $\begingroup$ 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? $\endgroup$ Jan 23 at 18:47
  • $\begingroup$ 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, $\endgroup$ Jan 23 at 19:04

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.