2

Just like deleting a line with ctrl+d or something else in normal coding, is there some shortcut to delete a whole cell?

narip
  • 381
  • 1
  • 9
  • 2
    Select the cell bracket (on the far right edge of the cell) and press the Delete key? – LouisB Apr 09 '22 at 07:40
  • 1
    I don't like to use a mouse lol. – narip Apr 09 '22 at 08:20
  • 2
    First, press Ctrl+. (ctrl-period) a few times until the cell bracket is highlighted. Second, use the up/down arrow keys to navigate to the cell you want to delete. Finally, press Delete. If you change your mind before you press Delete, cancel the selection using the the left arrow. – LouisB Apr 09 '22 at 09:11
  • @LouisB Thanks, but seems the shortcut should be ctrl+shift+. at least for me. – narip Apr 09 '22 at 10:59
  • 1
    Find this link useful. – narip Apr 13 '22 at 12:11

1 Answers1

4

The command below will temporarily put a 'Delete cell' action on the Insert menu which can be activated with ctrl+k. It only persists for the current session.

If your cursor is initially positioned between cells activation will delete the cell below.

FrontEndExecute[FrontEnd`AddMenuCommands[
  "DuplicatePreviousOutput", {Delimiter,
   MenuItem["Delete cell", FrontEnd`KernelExecute[
     Module[{nb},
      nb = SelectedNotebook[];
      SelectionMove[nb, Previous, Cell];
      SelectionMove[nb, Next, Cell];
      NotebookDelete[nb];
      SelectionMove[nb, Next, Cell]
     ]],
    MenuKey["k", Modifiers -> {"Control"}],
    System`MenuEvaluator -> Automatic]}]]

To make it a permanent menu item add the following to MenuSetup.tr. (Make a backup first though.)

Item["Delete cell", KernelExecute[
  Module[{nb},
   nb = SelectedNotebook[];
   SelectionMove[nb, Previous, Cell];
   SelectionMove[nb, Next, Cell];
   NotebookDelete[nb];
   SelectionMove[nb, Next, Cell]
  ]],
 MenuKey["k", Modifiers -> {"Control"}],
 MenuEvaluator -> Automatic]

I can see myself adopting this useful function.

ref. How can I set a keyboard shortcut to run a command?

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
  • Thank you for your answer, I still have two points unget. First, I don't know the exact place of MenuSetup.tr to add, there are too many Menu["..."] inside, and nested. Second, if I use the first command, should I also add it into MenuSetup.tr? – narip Apr 09 '22 at 08:40
  • Hi. You should only add the second command to MenuSetup.tr – Chris Degnen Apr 09 '22 at 10:16
  • Alternatively, save the first commend as a package, e.g. 'Delete cell.m' and load it with preinitialisation, i.e. set by InitializationValue[$PreInitialization] = Hold[Get[FileNameJoin[{$HomeDirectory, "Documents", "Delete cell.m"}]]] That will load 'Delete cell.m' every time Mathematica is started. Seems to slow down startup a bit though. – Chris Degnen Apr 09 '22 at 10:32
  • TextResources\MenuSetup.tr does not seem to exist in FileNameJoin[{$UserBaseDirectory, "SystemFiles", "FrontEnd"}] on version 13 for Macs. – Chris Degnen Apr 09 '22 at 10:42