# Code request: Make “copy formatted code” bulletproof

With the GeneralUtilitiesPrintDefinitions functions comes a usable code formatting engine. On this site, most of the time we share code. I believe it would be awesome to have a robust button that lets you copy selected code or cells directly to clipboard and make pasting more easy.

Look for instance at this small function:

<< GeneralUtilities
Button["Print Formatted Code",
Print[
DisplayForm[
MakeFormattedBoxes @@ MakeExpression[CurrentValue["SelectionData"]]
]
]
]


It has some major flaws (it doesn't preserve strings, it adds contexts, etc..) but it gives a head start. With it, you can select a portion of code (not a cell) and get a reformatted version. The above code block was created with it.

It can turn this

{0.872454,0.687674,0.127934,0.544796,0.522242,0.699434,0.0290001,0.111096,0.904602,0.0470287,0.309469,0.664936,0.613936,0.256512,0.247723,0.0429109,0.275135,0.907288,0.381302,0.142904}


into this

{
0.8724536302414463, 0.6876741664055988, 0.12793381311984442, 0.5447962818014034,
0.5222421222710214, 0.6994341188236166, 0.02900006229926766, 0.11109627731891036,
0.9046020599101727, 0.04702874732980167, 0.3094690356201151, 0.664935721568001,
0.6139357391996489, 0.25651232073953256, 0.24772295896395002, 0.04291086493297902,
0.2751346161611363, 0.9072882664480462, 0.3813024502288167, 0.14290372799071482
}


Not perfect, but a start.

Question: Can we create a robust "Copy code to clipboard" button that handles all use-cases and copies a reformatted version of the selection to the clipboard? It should not rely on additional packages (like Leonids code formatter) but it should reuse what is provided by the GeneralUtilities package.

## Reformatting expressions

If we have the code as expression and not as Cell[..] we can look into the implementation of MakeFormattedBoxes. Especially the function

GeneralUtilitiesFormattingPackagePrivatefullbox


is very interesting as it contains all rules that are applied to turn an expression into its reformatted box form. Spelunking there, we find how the reformatter

• includes context names in the code (sn)
• adjusts that f[x] is turned into f@x (syntax)
• make e.g. Or displayed as either Or[..] or x||y

Below is an image of the code, because SE breaks it with dollar variables. You can get the code with

Import["http://halirutan.github.io/Mathematica-SE-Tools/decode.m"]["http://i.stack.imgur.com/IsY34.png"]


• It appears I don't have MakeFormattedBoxes in version 10.1.0 but +1 for an interesting question! – Mr.Wizard Feb 23 '17 at 11:22
• Could you outline requirements for a valid answer? I'm not sure I got the point. Moreover, the fundamental problem with those tools is that they work with expressions (afaict) so no original choices about operators form used is preserved (f[x] vs f@x vs f//x). Another major issue is that comments will be stripped. – Kuba Sep 14 '17 at 8:53