18

is it possible to use the \url command from the hyperref package with "shorthand" URLs, e.g.

\url{ipython.org}

instead of

\url{http://ipython.org} ?

It seems that the former would only link to local files on my computer, instead of retrieving the web address. (I suppose I could be using \href, but \url is shorter and I'd like to keep its formatting features.)

Edit in response to karlkoeller's answer:

Sorry for not being sufficiently precise. I don't mind typing the 'http' part so much, but I'd rather not see it printed.

egreg's answer does what I want to do - many thanks!

17

It's better to use a different command, so that its usage is clear:

\documentclass{article}
\usepackage{xcolor}
\usepackage[
  colorlinks,
  linkcolor=magenta
]{hyperref}
\newcommand\rurl[1]{%
  \href{http://#1}{\nolinkurl{#1}}%
}

\begin{document}
This is a link \rurl{ipython.org} written in abbreviated form.
\end{document}

Of course you lose the tricks \url and \href are able to do with complex URI, for handling special characters, but short URI like this one should not have this problem.

The color in the image shows that it's indeed a link to a Web page.

enter image description here

  • Is there a way to make this work with urls like http://domain.tld?a=b&c=12_23#target, i.e. containing special characters? – Tobi Jan 19 at 10:40
  • @Tobi Not from the top of my head. – egreg Jan 19 at 10:48
10

You can load the package url and redefine the command \url as follows:

\DeclareUrlCommand\url{\color{magenta}\def\UrlLeft{http://}\urlstyle{tt}}

Note that the xcolor package is required, too, if you want to give a color to the link.

Now you can simply write

\url{ipython.org}

and http:// is added automatically.

Complete example

\documentclass{article}
\usepackage{hyperref}

\usepackage{xcolor,url}

\DeclareUrlCommand\url{\color{magenta}\def\UrlLeft{http://}\urlstyle{tt}}

\begin{document}

\url{ipython.org}

\end{document} 

Output:

enter image description here


Of course, you can leave the \url command as is and define a new command \shorturl so to have

\documentclass{article}
\usepackage[colorlinks]{hyperref}

\usepackage{xcolor,url}

\DeclareUrlCommand\shorturl{\color{magenta}\def\UrlLeft{http://}\urlstyle{tt}}

\begin{document}

\url{local-link}

\shorturl{ipython.org}

\end{document} 

Output:

enter image description here

  • 1
    uh, I think the request was for a printed version without the visible http://. – barbara beeton Oct 21 '13 at 23:04
  • @barbarabeeton you're right, I'm seeing it now. But the question wasn't so clear to me before the OP edited the original post. And the only way I know to achieve this is already in egreg's answer... – karlkoeller Oct 23 '13 at 14:30

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.