I need to use some colors frequently so I decided to make a palette for this. This is an example palette button that inserts a color:

CreatePalette[PasteButton[RGBColor[.5, .6, .7], RGBColor[.5, .6, .7]]]

But I may also want to set some text inside a non input cell to that color. So for that this works:

  Button[RGBColor[.5, .6, .7], 
                       RGBColor[.5, .6, .7]]}]]]


  Button[RGBColor[.5, .6, .7], 
    CurrentValue[NotebookSelection[InputNotebook[]], FontColor] = RGBColor[.5, .6, .7]]]

But I don't want two create two buttons for each color. I prefer to have a single button that inserts a color if nothing is selected (1st case) or styles some text is there is a selection.

This is what I have tried to do (but it does not work):

  Button[RGBColor[.5, .6, .7],
    If[CurrentValue["SelectionData"] == $Failed,
       NotebookWrite[ButtonNotebook[], RGBColor[.5, .6, .7]],
       FrontEndExecute[{FrontEndToken[InputNotebook[], FontColor, RGBColor[.5, .6, .7]]}]]]]

Can this be solved?


This works for me:

CreatePalette[Button["Crazy Color Palette",
  ib := InputNotebook[];
  If[NotebookRead[ib] === {},
     NotebookWrite[ib, "RGBColor[.5,.6,.7]"], 
     FrontEndExecute[{FrontEndToken[ib, FontColor, RGBColor[.5, .6, .7]]}]]]]

enter image description here

| improve this answer | |
  • $\begingroup$ thanks for the answer, but it does not solve the problem. Try your palette in a single word in a text cell and it gets replaced by RGBColor[.5,.6,.7] insteas of being styled in that color. $\endgroup$ – Gustavo Delfino Sep 23 '15 at 12:59
  • $\begingroup$ @GustavoDelfino Try it now, please $\endgroup$ – Dr. belisarius Sep 23 '15 at 13:40
  • $\begingroup$ Yes! It now works. I now see that you used SetDelayed inside the palette. Nice! $\endgroup$ – Gustavo Delfino Sep 23 '15 at 18:37

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.