35

Is there a command / menu entry / keyboard shortcut to evaluate all cells above / up to the current cursor position? I have the feeling I am missing something elementary here...

Addendum: In fact, it is more about selection of those cells, evaluation is not the problem as such.

Yves Klett
  • 15,383
  • 5
  • 57
  • 124
  • Shift-Home Shift-Enter maybe? (on a keyboard that has Home) – rm -rf Dec 20 '12 at 14:38
  • @rm-rf nope... no luck here (Win 7 64bit). But it is kind of elementary, right? Often I just want to evaluate up to a certain point, and selecting all cells upwards with the mouse or keyboard seems suboptimal. – Yves Klett Dec 20 '12 at 14:41
  • On my mac, keeping the cursor under one cell (horizontal cursor) and then holding shift and selecting the next cell will select everything in between, no need to drag (but becomes a pain for large notebooks). I wonder why the Home key doesn't work though... Mr.Wizard indicated here that he uses them – rm -rf Dec 20 '12 at 14:48
  • @rm-rf the shift thing between cells works here as well, but moving to the beginning with lots of dragging dynamic stuff is painful indeed. – Yves Klett Dec 20 '12 at 14:52
  • In a reasonably organized notebook, those preceding cells are probably within sections and subsections of their own, with the current cell, the one above which you wish to evaluate, in a new section or subsection. So just collapse those preceding sections or subsections, select their group brackets, and then do an evaluation. – murray Dec 20 '12 at 15:42
  • A couple of thoughts. With cells now being objects does that make it easier to locate and select cells. (I haven't tested this feature in 9 yet). MousePosition with "DocumentAbsolute" to identify the position of the horizontal cursor? – Mike Honeychurch Dec 20 '12 at 21:31
  • @rm-rf Home and End work within cells. To move to the beginning or end of a Notebook I need Ctrl + Home or Ctrl + End. I had hoped that Ctrl + Shift + Home would work but it does not; the cursor moves but nothing is selected. – Mr.Wizard Dec 21 '12 at 07:33
  • @murray even if a notebook were perfectly organized (and I confess I have a few imperfect ones lurking around) closed cells sometimes open up again during evaluation (subjectively in combination with Dynamic stuff) - so re-closing those each time is not attractive. To me, wanting to select all cells up to certain point feels like a really straightforward wish, but one that is obviously not that much in demand. – Yves Klett Dec 21 '12 at 18:52
  • 3
    EXTREMELY useful! I've been suggesting this feature to WRI for several years. – Andreas Lauschke Dec 21 '12 at 20:08
  • 1
    @AndreasLauschke phew, glad I´m not the only one. And it seems such a minor effort to add this to the menu/shortcuts. Whom at WRI should we bug to reinforce your effort? – Yves Klett Dec 21 '12 at 20:16
  • 2
    Useless. Forgeddaboudit. But you could put Rolf's or Martin's or Rojo's solution in an init.m, to put it on a button in a palette, or use the keytranslate. I have no use for the Caps Lock key, I find it the most useless key ever, so I mull putting this on Caps Lock. Solves two problems at once, and turns them into solutions. I don't like overloading Shift and Ctrl keys too much, as I have other key translations for them on an o/s level, but Caps Lock is free and otherwise useless. – Andreas Lauschke Dec 21 '12 at 20:25
  • 1
    @AndreasLauschke I like the Caps Lock two-in-one fix. No more unneccessary sHOUTING as well! Hmm, a productive evening. – Yves Klett Dec 21 '12 at 20:30

5 Answers5

28

One possibility is to modify your personal KeyEventTranslations.tr (only tested on Windows). Evaluate the following, then restart Mathematica, then Ctrl+Shift+Home will select all cells above the insertion point.


For 9.0.1. use: Import["http://www.mertig.com/shortcuts.m"]


    mymenuitems="
         (* Select all cells upwards *)
         Item[KeyEvent[\"Home\", Modifiers -> {Control, Shift}], 
         KernelExecute[
          Module[{ enb = EvaluationNotebook[],
                   tag = StringJoin[\"tmp\", ToString[Round[AbsoluteTime[]/$TimeUnit]]],editable 
                       },
                    editable = ReplaceAll[Editable, Options[enb, Editable]];
                    SetOptions[enb, Editable -> False];
                    SelectionMove[enb, Previous, Cell, AutoScroll -> False];
                    MathLink`CallFrontEnd[FrontEnd`SelectionAddCellTags[enb, {tag}]];
                    SelectionMove[enb, Before, Notebook, AutoScroll -> False];
                    SelectionMove[enb, Next, Cell, AutoScroll -> False];
                    While[FreeQ[ReplaceAll[CellTags,Options[NotebookSelection[]]], tag],
                          MathLink`CallFrontEnd[FrontEnd`SelectionAddCellTags[enb, {tag}]];
                          SelectionMove[enb, Next, Cell, AutoScroll -> False]
                    ];
                    NotebookFind[enb, tag, All, CellTags, AutoScroll -> False];
                    MathLink`CallFrontEnd[FrontEnd`SelectionRemoveCellTags[enb, {tag}]];
                    SetOptions[enb, Editable -> editable]
                ]
                ], MenuEvaluator -> Automatic ]
                ";
With[{os = Switch[$OperatingSystem,"MacOSX","Macintosh","Windows","Windows","Unix","X"]},
Quiet@CreateDirectory@FileNameJoin[{$UserBaseDirectory,"SystemFiles","FrontEnd","TextResources",os}];
    mykeyeventtrans=FileNameJoin[{$UserBaseDirectory,"SystemFiles","FrontEnd","TextResources",os,"KeyEventTranslations.tr"}];
    (*If[FileExistsQ[mykeyeventtrans],DeleteFile@mykeyeventtrans];*)
    If[!FileExistsQ[mykeyeventtrans],
    CopyFile[FileNameJoin[{$InstallationDirectory,"SystemFiles","FrontEnd","TextResources",os,"KeyEventTranslations.tr"}],mykeyeventtrans]
]];
keytext=Import[mykeyeventtrans,"Text"];
mykeytext=StringReplace[keytext,"EventTranslations[{":>StringJoin["EventTranslations[{\n(* User defined *)\n",mymenuitems,",\n"]];
Export[mykeyeventtrans,mykeytext,"Text"];
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
Rolf Mertig
  • 17,172
  • 1
  • 45
  • 76
  • 2
    (...drawing a deep breath...) AWESOME! This is pure gold, and with bells and whistles as well. My workflow sends most sincere regards and goes home early to celebrate. – Yves Klett Dec 21 '12 at 18:43
  • Still, I wonder why this is not in the standard edition - is it only me wanting to do this? – Yves Klett Dec 21 '12 at 18:56
  • 1
    @YvesKlett Gern geschehen. I actually added SelectionEvaluate[SelectedNotebook[]]; at the end of KernelExecute, since I usually like to do that. It is a matter of personal working style I guess if one wants this or not. Maybe people at WRI work differently? Or have smaller notebooks? Or don't use notebooks really for testing (being WWB freaks all of them?). Who knows. At least it is sufficiently easy to modify/improve things in Mathematica. – Rolf Mertig Dec 21 '12 at 19:00
  • 2
    slightly modified to work also under Linux correctly ... Notice that I personally find Control Shift UpKey easier. So what I use can be used like Import["http://www.mertig.com/shortcuts.m"] – Rolf Mertig Dec 22 '12 at 22:22
  • 2
    Updated the comments for 9.0.1. Use: Import["http://www.mertig.com/shortcuts.m"] – Rolf Mertig Feb 18 '13 at 16:57
  • 1
    Very, very nice. The given code can be (very) slightly modified to create a shortcut that selects all cells below the current cell, using Ctrl+Shift+DownArrow. After the definition of mymenuitems, just add the following line: mymenuitems=StringReplace[mymenuitems, {"Home" -> "Down","Next" -> "Previous", "Previous" -> "Next", "Before" -> "After"}];. – Eric Thewalt Mar 13 '13 at 08:39
  • Have you tested this in version 10.0 or 10.1 yet? – Mr.Wizard May 16 '15 at 07:09
  • @Mr.Wizard I am doing this and refactoring the whole setup into a proper package (to be put on github). If there are wishes, you may all post them or send me mail. I already have a keyboard shortcut (Ctrl r) to restart the whole FrontEnd. And another keyboard shurtcut (with Kuba's help) to only restart the kernel. Stay tuned. – Rolf Mertig May 22 '15 at 13:21
  • I haven't been able to implement this on 10.0. Could you please be a bit more specific on how to include the code you give? If I add it as is to KeyEventTranslations.m, it corrupts it. – usumdelphini Jan 16 '19 at 10:09
  • Just run from within a Mathematica notebook Import["http://www.mertig.com/shortcuts.m"] – Rolf Mertig Jan 16 '19 at 12:35
  • Thanks! with slightly changes, it works for me on mac, MMA 13.2. – Lacia May 23 '23 at 15:02
  • What exactly did you change? – Rolf Mertig May 23 '23 at 19:30
6

This is a modification of @Kuba's answer, again evaluating all cells above and including the selected cell, but without the "beep" (a minor refinement). Thanks @Kuba for the main routine. As with the original, the code generates a dinky palette with a single "Evaluate Above" button, which may then placed at any convenient location (such as next to the other menu items at the top of your working notebook). A cell (any cell) must be selected for the "Evaluate Above" button to work.

CreatePalette[
 Button["Evaluate Above",
  With[{nbI = InputNotebook[]},
   Do[
    SelectionMove[Experimental`FromCellIndex[nbI, i], All, Cell];
     If[TextString["Style" /. Developer`CellInformation[nbI][[1]]] === "Input",
      SelectionEvaluateCreateCell[nbI]];,
     {i, 1, Experimental`ToCellIndex@SelectedCells[nbI][[1]]}]],Method -> "Queued"]]

The code change selects out only Input cells for evaluation, "skipping over" (generating a Null result) for all other cell styles. Thanks @John Fultz for the command that returns cell styles (under "How can I get the style of selected cells?"). Evidently, a "beep" would occur if non-input cells were asked to be evaluated. This seems to be working fine with Mathematica 11.0.1.

I'm new to Mathematica, and this thread has not been active for a while. So I'm not sure whether there is now some easy way to do this built in (can't find anything), or whether a custom routine like this is still required.

Update 3/10/18: I've added the Button option Method -> "Queued" in order to prevent the timeout that occurs with the default Button evaluation method "Preemptive." The "Queued" option is used to evaluate button functions on the main link, which never times out.

Bill N
  • 216
  • 3
  • 8
  • +1 you should have told me ;) I wasn't aware as I do not use it on daily basis ;) – Kuba Nov 22 '16 at 12:51
  • Sry @Kuba :) I'm so new here, I don't have enough points yet to even comment at your post (hehe). A big Thank You is coming once I do. This is a huge "hassle factor" reducer. – Bill N Nov 22 '16 at 13:49
  • 1
    Thank you for the update. I am not aware of any changes in the frontend to facilitate that, but I am very happy with Rolf's solution. – Yves Klett Nov 27 '16 at 07:39
  • @Yves Klett Thanks for letting me know that a custom function is still required. – Bill N Nov 27 '16 at 13:41
  • @BillN welcome to the party :D – Yves Klett Nov 27 '16 at 18:22
6

I was just working on something and here's a side effect. Nothing new but given in closed form as palette button:

CreatePalette[
 Button["Evaluate above",
  With[{NB = InputNotebook[]},
   Do[ SelectionMove[Experimental`FromCellIndex[NB, i], All, Cell];
       SelectionEvaluate[NB];
       , {i, 1, Experimental`ToCellIndex @ SelectedCells[NB][[1]]}]
   ]]]

Cursor must not be between cells but in the cell that is meant to be evaluated at the end.

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • Thank You so very much for this massive time saver you came up with! (Hehe, I finally got enough points to thank you). As you are aware, I modified your routine slightly in order to get rid of the "beep," and posted the mod below. I don't use MMA often enough to remember a bunch of Key Commands, so it's nice to have a nifty little palette with the one "Evaluate Above" button on it that I can conveniently place anywhere. – Bill N Nov 25 '16 at 17:31
  • @BillN No problem :) Good luck and I hope you will come here more often :) Not only to fix my answers :) – Kuba Nov 26 '16 at 14:18
2

You can evaluate the input cells before the current cell by running this

Function[cobj,
   SelectionMove[cobj, Cell, All];
   SelectionEvaluate[InputNotebook[]];]~
  Scan~
  TakeWhile[Cells[CellStyle -> "Input"], # =!= EvaluationCell[] &];
SelectionMove[EvaluationCell[], After, Cell];
Rojo
  • 42,601
  • 7
  • 96
  • 188
1

I have no idea how to do this with relation to the cursor in general, but using CellObject you can do a lot if you're in a cell.

There's quite a bit you can do with the SelectionMove function. The following will select all the cells in the evaluation notebook. Note that quite strangely All is specifying the current notebook, After and Previous will give you the respective element of the list of notebooks provided by evaluating Notebooks[].

SelectionMove[EvaluationNotebook[], All, Notebook]

The selection can be moved according to CellGroup. This button will progressively select each CellGroup above the button:

Button["Select previous cell group", SelectionMove[EvaluationNotebook[], Previous, CellGroup]]

The documentation for the SelectionMove function provides quite a few examples, and shows the function can be used to select the internal contents of a cell as well as entire cells.

I think there's a way I can get Mathematica to give me the list of CellObject prior to the first of the SelectedCells but I'm not quite there yet.

Charlotte Hadley
  • 2,364
  • 19
  • 17
  • Most@ExperimentalCellRange[First, EvaluationCell[]]. Or with only documented functions,TakeWhile[Cells[], # =!= EvaluationCell[] &] == Most@ExperimentalCellRange[First, EvaluationCell[]] – Rojo Dec 21 '12 at 11:12
  • Sorry, I thought it was before hte evaluating cell, use SelectedCell[] instead for the selected cell – Rojo Dec 21 '12 at 11:13
  • That's pretty cool, I'll need to play around with CellRange. I can't believe the Experimental context shows in the command completion menu now. – Charlotte Hadley Dec 21 '12 at 11:46
  • @Rojo your first comment ate up a context backtick and the rest does not really work on V9 here... would you care to elaborate? – Yves Klett Dec 21 '12 at 18:49
  • Yes, sorry, Most@Experimental\CellRange[First, EvaluationCell[]]. Or with only documented functions,TakeWhile[Cells[], # =!= EvaluationCell[] &]. That should give a list of theCellObjects` before the evaluating one. – Rojo Dec 21 '12 at 18:52
  • @Rojo and then how to evaluate those? I feel you have an answer waiting to happen :-) – Yves Klett Dec 21 '12 at 18:55
  • There must be easier ways, but at least you can do it with a Scan. If that is an answer to your question, I'm posting it – Rojo Dec 21 '12 at 19:13