9
$\begingroup$

In my text editor, Mathematica code may look like this:

enter image description here

YMMV, of course, but I at least find this easy to read.


If I copy that snippet of code and paste into a Mathematica notebook, it looks like this:

enter image description here

...which I find much harder to read, even for a short code snippet like this one. For the much longer chunks of code I typically work with, pasting them into a notebook renders them basically unreadable.

Is there a way to paste pre-formatted code into Mathematica verbatim?

$\endgroup$
9
$\begingroup$

Here is some Mathematica code as it appears after writing it my text editor.

bbedit

In a Mathematica note book I create a new Code cell with Cmd+8 (in OS X), and paste the code from the text editor into the cell. The gray background indicates the cell has the initialization cell property. Don't want that.

init_cell

With the mouse cursor in the Code cell (or with the cell selected), hit Ctrl+8. The gray background vanishes. The cell no longer has the initialization cell property. It behaves like an input cell except it maintains the plain text formatting.

code_cell

If you were to copy this code from a Mathematica notebook and paste it into one of this site's editing panes, it would still maintains its line formatting, so all that is needed after pasting is select the code and hit Cmd+K to get the following.

foo[x_, y_]:=
  (* This is a comment *)
  Module[{bar = {x, y}, this, that},
    {this, that} = Thread[frob[bar]];
    1 + this/that]

Update

Using Ctrl+8 may only work on OS X. The only indication of this keyboard shortcut comes from the Cell menu itself. See bellow

menu

The ^8 appearing on right side of the indicated menu item is OS X's way of showing Ctrl+8 is available as a shortcut.

$\endgroup$
  • $\begingroup$ @Kuba. Get a Mac :-) $\endgroup$ – m_goldberg Mar 3 '17 at 16:25
  • $\begingroup$ @Kuba. It toggles the initialization code property of the cell. Very handy. See my update. $\endgroup$ – m_goldberg Mar 3 '17 at 16:43
  • 2
    $\begingroup$ I like the "Code" style so much, but don't want to answer about "Initialization cells" and whether I want to run them every time I open the notebook. So I have a custom "NoInitCode" style in my default style sheet $\endgroup$ – Jason B. Mar 3 '17 at 17:15
  • $\begingroup$ @JasonB: Can you bind that style to a keyboard shortcut (like Alt+8, etc.)? $\endgroup$ – kjo Mar 3 '17 at 19:31
  • $\begingroup$ I do, I have it set to Cmd-Shift-8 $\endgroup$ – Jason B. Mar 3 '17 at 19:32

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.