Joachim Breitner's Homepage
Nicer URL formatting in LaTeX
To format URLs in LaTeX, one usually uses the url package (either directly, or indirectly via hyperref). By default, it typesets the URL in a mono-spaced font. Maybe this was a good idea some years ago, when URL were not ubiquitous. Today, I do not think they need neither the emphasis nor the explictit technical association that is caused by changing the font. And last but not least, mono-spaced fonts are very wide.
So url
offers the command \urlstyle
. I prefer to set it to sf
, because URLs tend to look better without serif. In the picture above (also available as PDF), that is the second line. But this still has issues: The double slash at the beginning is spaced out more than it should, given that, at least to most readers, http://
is a single entitiy. In addition, the underscore is far to wide (this only happens if you use the T1 font encoding).
Hence I modified the typesetting of both the slash and the underscore to achieve the appearance in the third line. The code is derived from the one given on this blog post by Nei, with slightly less kerning of the slashes and with extending instead of redefining \UrlSpecials
and the underscore handling added. Here is the full code for the picture given above, to use it you need to copy the part between and including \makeatletter
and \makeatother
into the preamble of your document:
\documentclass{article} \usepackage{url} \usepackage[T1]{fontenc} \usepackage[top=3pt, bottom=3pt, left=3pt, right=3pt, paperwidth=6.7cm, paperheight=1.6cm]{geometry} \begin{document} \noindent \url{http://example.com/with_underscore/}\\ \urlstyle{sf} \url{http://example.com/with_underscore/}\\ \makeatletter % Inspired by http://anti.teamidiot.de/nei/2009/09/latex_url_slash_spacingkerning/ % but slightly less kern and shorter underscore \let\UrlSpecialsOld\UrlSpecials \def\UrlSpecials{\UrlSpecialsOld\do\/{\Url@slash}\do\_{\Url@underscore}}% \def\Url@slash{\@ifnextchar/{\kern-.11em\mathchar47\kern-.2em}% {\kern-.0em\mathchar47\kern-.08em\penalty\UrlBigBreakPenalty}} \def\Url@underscore{\nfss@text{\leavevmode \kern.06em\vbox{\hrule\@width.3em}}} \makeatother \url{http://example.com/with_underscore/} \end{document}
Comments
\def\Url@underscore{\nfss@text{\BeginAccSupp{ActualText=_,space}\leavevmode \kern.06em\vbox{\hrule\@width.3em}\EndAccSupp{}}}
Anyway, thank you very much for the hint!
Thanks a lot for this. The url package allows for line breaks after underscores. However, this does not work with the replacement you suggest. I managed to fix this by adding
\linebreak[1]
in the definition
of \Url@underscore
as follows:
\def\Url@underscore{\nfss@text{\leavevmode\kern.06em\vbox{\hrule\@width.3em}}\linebreak[1]}
Have something to say? You can post a comment by sending an e-Mail to me at <mail@joachim-breitner.de>, and I will include it here.