Paste Mathematica code so that's it's broken into separate input cells

前端 未结 2 733
-上瘾入骨i
-上瘾入骨i 2021-01-02 14:38

I often copy Mathematica code from websites (such as SO) to a notebook. The code usually gets pasted as a single input cell. I\'m looking for a simple way to paste it as s

相关标签:
2条回答
  • 2021-01-02 15:19

    Or.... you can just Hit Ctrl+Shift+D at the point where you'd like to split your singe cell into 2 separate cells. Some times it's advantageous to group multiple operations into a single cell (or rather not split them to begin with). To undo such a split, select both cells (or more than 2 if you'd like) and click Ctrl+Shift+M to merge them into one.

    0 讨论(0)
  • 2021-01-02 15:35

    This is a simple implementation (I'd also appreciate a code review, I'm not good in front end programming):

    (* This converts a sequence of expressions into boxes *)
    Clear[makeManyBoxes]
    SetAttributes[makeManyBoxes, HoldAllComplete];
    makeManyBoxes[e__] := List@ReleaseHold[MakeBoxes /@ HoldComplete[e]]
    
    (* Split a list at separator *)
    split[list_, sep_] := 
     DeleteCases[Split[list, #1 =!= sep && #2 =!= sep &], {sep}] 
    
    wr[e_] := NotebookWrite[InputNotebook[], Cell[BoxData[e], "Input"]]
    
    CreatePalette@Button["Paste!",
      Module[{clipboard},
       clipboard = NotebookGet[ClipboardNotebook[]][[1, 1, 1]];
       If[StringQ[clipboard],
    
        wr /@ 
         split[ToExpression[clipboard, InputForm, makeManyBoxes], "Null"]
        ]
       ]
      ]
    

    It breaks cells at empty lines. For this, we need to parse the expression first (what if an empty line appears in the middle of a long Module?). But parsing alone will cause several problems.

    Problems with this implementation:

    • it removes comments
    • it can't handle incorrect inputs
    • it doesn't preserve the formatting (newlines)
    • I'm sure there must be several other things that can go wrong
    0 讨论(0)
提交回复
热议问题