8
$\begingroup$

Consider the following example:

ClickToCopy["display text","file name"]

When I click the display text I get "file name" rather than file name without the quotes. Which doesn't serve my purpose of quick file name access. So when I copy to some location I have to manually remove the quotes.

What should I do to make it copy the actual Text inside the String?

$\endgroup$
7
  • 1
    $\begingroup$ ClickToCopy["display text",Defer[ file name]]? $\endgroup$
    – kglr
    Commented Feb 3, 2021 at 3:48
  • $\begingroup$ .. or ClickToCopy["display text",ToExpression["file name",StandardForm, HoldForm]]? $\endgroup$
    – kglr
    Commented Feb 3, 2021 at 4:00
  • $\begingroup$ @kglr the text needs to be copied into a different program. So if I use the second one I get \!(TagBox[RowBox[{"file", " ", "name"}],HoldForm]) which is not correct. $\endgroup$
    – user13892
    Commented Feb 3, 2021 at 6:45
  • $\begingroup$ The first one works by modifying to ClickToCopy["display text", Defer[Evaluate[ToExpression["file name"]]]] and produces the text of the string on copy. $\endgroup$
    – user13892
    Commented Feb 3, 2021 at 6:47
  • 1
    $\begingroup$ try if Button["display text",CopyToClipboard["file name"], Appearance->None] works? $\endgroup$
    – kglr
    Commented Feb 3, 2021 at 6:56

4 Answers 4

7
$\begingroup$

You can use CopyToClipboard:

Button["display text", CopyToClipboard["file name"], Appearance -> Frameless]

CopyToClipboard >> Scope

"Copying a string copies the contents of the string."

Column @ MapThread[Button[#, CopyToClipboard @ #2, Appearance -> Frameless] &, 
    {{"display text 1", "display text 2"}, {"file name", "Alex E"}}]

enter image description here

enter image description here

$\endgroup$
1
  • $\begingroup$ This is really nice and will do the job. But I wish there was a way to get ClickToCopy to work. I really liked the ClickToCopy appearance on hover and click. I will raise this issue in the next SW Livestream. They could easily make the click to copy the content of the string rather than the string object via some option perhaps. $\endgroup$
    – user13892
    Commented Feb 3, 2021 at 7:27
3
$\begingroup$

I think you can just use RawBoxes, e.g.:

ClickToCopy["display text", RawBoxes@"file name"]
$\endgroup$
1
  • $\begingroup$ This is the way. Though I must admit that this is a bit obscure! $\endgroup$
    – SHuisman
    Commented Jul 17, 2023 at 13:33
1
$\begingroup$

The style definition of ClickToCopy can be found in the following stylesheet

FileNameJoin@{$InstallationDirectory,"SystemFiles","FrontEnd","StyleSheets","Core.nb"}

and uses CopyToClipboard

...
ButtonBox[
    ...
    CopyToClipboard[Cell[BoxData[#2],"Input"]]
    ...
]
...

where the double quotes come from.

Hence we can try to define a new function by slightly modifying ClickToCopy, and this has almost been done. The undocumented function CloudObject`Private`customClickToCopy has essentially the same definition but different options as CopyToClipboard,

Needs["CloudObject`"];
CloudObject`Private`customClickToCopy[#,Hold[#]]&@"test"

enter image description here

With slight efforts we have

clickToCopyText[displayedText_] :=
    clickToCopyText`kernel[displayedText,displayedText];
clickToCopyText[displayedText_,copiedText_] :=
    clickToCopyText`kernel[displayedText,copiedText];


clickToCopyText`kernel[displayedText_,copiedText_] :=
    Mouseover[
        clickToCopyText`makeClickToCopyOverlay[displayedText,None],
        DynamicModule[{Typeset`boxobj,Typeset`cellobj},
            EventHandler[
                Button[
                    clickToCopyText`makeClickToCopyOverlay[displayedText,clickToCopyText`aliceBlue],
                    CopyToClipboard@copiedText;
                    NotebookDelete@Typeset`cellobj;
                    Typeset`cellobj =
                        MathLink`CallFrontEnd@FrontEnd`AttachCell[
                            Typeset`boxobj,
                            Cell@BoxData@TemplateBox[{"Copied"},"ClickToCopyTooltip"],
                            {1,{Center,Bottom}},
                            {Center,Top},
                            "ClosingActions"->{"ParentChanged"}
                        ],
                    Appearance->FrontEndResource["FEExpressions","SuppressMouseDownNinePatchAppearance"],
                    BaseStyle->{},
                    Alignment->{Left,Automatic},
                    DefaultBaseStyle->{},
                    BaselinePosition->Baseline,
                    FrameMargins->0,
                    Method->"Preemptive"
                ],
                {
                    "MouseEntered":>(
                        Typeset`cellobj =
                            MathLink`CallFrontEnd@FrontEnd`AttachCell[
                                Typeset`boxobj,
                                Cell@BoxData@TemplateBox[{"Copy"},"ClickToCopyTooltip"],
                                {1,{Center,Bottom}},
                                {Center,Top},
                                "ClosingActions"->{"ParentChanged"}
                            ]
                    ),
                    "MouseExited":>NotebookDelete[Typeset`cellobj]
                },
                PassEventsDown->True
            ]//MouseAppearance[#,"LinkHand"]&,
            Initialization:>(
                Typeset`boxobj = EvaluationBox[]
            ),
            UnsavedVariables:>{Typeset`boxobj,Typeset`cellobj},
            BaseStyle->{Editable->False}
        ]
    ];

clickToCopyText`makeClickToCopyOverlay[text_,bgColor_] :=
    Framed[
        text,
        Background->bgColor,
        FrameStyle->bgColor,
        "BoxExpandable"->True,
        BaseStyle->{},
        DefaultBaseStyle->{},
        Alignment->{Left,Automatic},
        BaselinePosition->Baseline,
        FrameMargins->0
    ];

clickToCopyText`aliceBlue = N@RGBColor[{232,243,255}/255];

Now let's test,

testString=(SeedRandom[1];RandomWord[20]//StringRiffle)

test={{"clickToCopyText",clickToCopyText@testString},{"ClickToCopy",ClickToCopy@testString},{"plain",testString}};
test//Grid

enter image description here

and the pasted text contains no double quotes as expected.

Drawback

I take several hours on the compatibility of clickToCopyText|ClickToCopy with Dataset, but failed,

test//Dataset

enter image description here

The text font can be easily fixed by the options

BaseStyle->{FontFamily->"Source Sans Pro",FontSize->14,FontWeight->Plain}

But for ClickToCopy, sometimes (maybe according to the type system of Dataset) there are double quotes appearing in the dataset by the cell option

ShowStringCharacters->True

For my clickToCopyText, the text will be hidden if too long, and I have no idea how to fix it by clickToCopyText or options of Dataset.

$\endgroup$
0
$\begingroup$

This is not an answer, for reference only, you can use the following method to paste the contents of the pasteboard to MMA:

   PastContent[] := 
     NETLink`NETBlock[
      Block[{img, width, Width, height, Height, LockBits, PixelFormat, 
        Format24bppRgb, stride, Stride, Scan0, totalB, byte, intPtr, data,
         UnlockBits, lock}, Needs["NETLink`"]; NETLink`InstallNET[];
       NETLink`LoadNETType["System.Windows.Forms.Clipboard"];
       Which[Clipboard`ContainsText[], 
        If[Clipboard`GetText[] // 
          StringStartsQ[#, "\\!\\("] && StringEndsQ[#, "\\)"] &, 
         ToExpression[Clipboard`GetText[]], Clipboard`GetText[]], 
        Clipboard`ContainsImage[], 
        NETLink`LoadNETType /@ {"System.Drawing.Rectangle", 
          "System.Drawing.Imaging.ImageLockMode", 
          "System.Runtime.InteropServices.Marshal"};
        img = Clipboard`GetImage[];
        width = img[Width]; height = img[Height];
        lock = 
         img[LockBits[Rectangle`FromLTRB[0, 0, width, height], 
           ImageLockMode`ReadWrite, img[PixelFormat][Format24bppRgb]]];
        stride = Abs[lock[Stride]]; intPtr = lock[Scan0];
        totalB = stride*height;
        byte = NETLink`NETNew["System.Byte[]", totalB];
        Marshal`Copy[intPtr, byte, 0, totalB];
        data = NETLink`NETObjectToExpression[byte];
        Marshal`Copy[byte, 0, intPtr, totalB]; img[UnlockBits[lock]];
        Image[
         Map[Reverse /@ Partition[#, 3] &, 
          Partition[data, width*3, stride]], "Byte"], 
        Clipboard`ContainsFileDropList[], 
        NETLink`NETObjectToExpression[Clipboard`GetFileDropList[]]]]]

PastContent[]

I think you should post the code of function ClickToCopy for us to revise.

$\endgroup$
4
  • 2
    $\begingroup$ ClickToCopy is built-in. $\endgroup$
    – MarcoB
    Commented Feb 3, 2021 at 5:12
  • $\begingroup$ @MarcoB Thank you for your reminding. I use version 12.1, and this function is a new function in version 12.2. $\endgroup$ Commented Feb 3, 2021 at 5:17
  • 4
    $\begingroup$ This isn't an answer, then why not post a comment with the link to this function?: mmaqa.com/qa/1731/mmaexcelmma?show=1773#a1773 $\endgroup$
    – xzczd
    Commented Feb 3, 2021 at 6:24
  • $\begingroup$ @xzczd Sorry, this is my negligence. Thank you for your supplementary information. $\endgroup$ Commented Feb 3, 2021 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.