To make this working reliable with links in input-cells, links created with Hyperlink
or links created with Insert->Hyperlink seems a mess, since all those links have a different nested structure.
Let me start easy: The next should definitely work with links that were created with Insert->Hyperlink (or Ctrl+Shift+H) in text or input cells.
The trick is to use Options
when the link is selected. First a simple test: Create a text-cell with a link in it and mark the link. Then press this button
Button["Options", Print@Options[NotebookSelection[SelectedNotebook[]]]]
and you get something like
{ButtonBoxOptions->{
BaseStyle->Hyperlink,
ButtonData->URL[http://www.wweb.de],None},
ButtonNote->http://www.web.de}
}
ButtonData
is the link of the target and I haven't tried to find out what the None
means. The ButtonNote
is the information which is displayed in the status bar of the notebook when you are over the link with the mouse.
Since we can use SetOptions
to change those settings the things left to do are to create a button which has the following behavior when pressed
- It extracts the
Options
of the selected expression.
- It checks whether this is a hyperlink.
- It pops up a
DialogInput
with the old value of the link which can be edited.
- It sets this new content using
SetOptions
.
Here we go
Button["Edit Hyperlink",
Block[{sel, data, opts, newlink},
sel = NotebookSelection[SelectedNotebook[]];
opts = Options[sel];
If[FreeQ[opts, ButtonBoxOptions],
MessageDialog["Couldn't identify hyperlink"],
data = ButtonData /. (ButtonBoxOptions /. opts);
newlink = DialogInput[{url = First[data]},
Column[{
"Target page",
InputField[Dynamic[url], Expression],
Button["OK", DialogReturn[url]]
}]
];
If[newlink =!= $Canceled && newlink =!= $Failed,
SetOptions[sel,
opts /. (ButtonData -> _) -> (ButtonData -> {newlink,
Last[data]})]
]
]], Method -> "Queued"
]
Links created with Hyperlink
This works too with the above code, the difficulty is to select the right expression. Try to create an example Hyperlink["A Link", "http://www.wolfram.com"]
and now use the arrow-keys to move the cursor inside the link (maybe between the L
and the i
) and then press Ctrl+. over and over again to extend the selection stepwise. It requires 6 times until I have selected the whole cell.
After hitting 4 times Extend Selection I have selected the right level of the expression and the Options button of my first code-block shows me
{Active->True, ButtonBoxOptions->{
BaseStyle->Hyperlink,
ButtonData->{URL[http://www.wolfram.com],None},
ButtonNote->http://www.wolfram.com}}
This is the right level, where the Edit Hyperlink will work.