# How to automatically trim a URL up to a certain length measured from the right?

## Current condition

A long URL makes a bad look as follows.

\documentclass{article}
\usepackage{xcolor,listings}
\lstset
{
language={[LaTeX]TeX},
backgroundcolor=\color{yellow!50},
breaklines=true,
}

\def\InputCode#1#2{%
\lstinputlisting[caption=\href{#2}{#2}]{#1}}

\begin{document}

\minipage{0.5\linewidth}
\InputCode{\jobname.tex}{http://www.oakfurniturehouse.co.uk/userfiles/image/3B4K1820.jpg}
\endminipage

\end{document}


## Expected Result

I want to trim the left part up to a certain length measured from the right as follows. The trimmed part will be replaced by ....

How to do this automatically because the minipage width can vary throughout my document.

-
Do you want an option like gobbleleft or a simple optional argument which required a number? –  Marco Daniel Sep 1 '12 at 9:27
@MarcoDaniel: I don't understand well your question. I just need the untrimmed part of the URL occupies in the available space of \linewidth-2\sideoffset where \sideoffset is used to make the URL look centered rather than fully justified. –  kiss my armpit Sep 1 '12 at 9:34

• do not use \def -- In the frontend it's more comfortable to use xparse.
• Combinations like \minipage --- \endminipage should be avoided. Use \begin{minipage} --- \end{minipage}.

Here a suggestion using the benefits of expl3. The following mechanism is used:

1. Save the url in a hbox and compare the with of the box with the required width.
2. If the width of the url is too long the url will be saved as a token list. Now the first token of the list will be removed and the result will be saved inside a hbox. And now see 1.

Here The code:

\listfiles
\documentclass{article}
\usepackage{xcolor,listings}
\lstset
{
language={[LaTeX]TeX},
backgroundcolor=\color{yellow!50},
breaklines=true,
}

\newlength\sideoffset
\setlength\sideoffset{2cm}

\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand \InputCode { m m }
{
\lstinputlisting
[caption=\href{#2}{
\hbox_set:Nn \l_tmpa_box { #2 }
\dim_compare:nNnTF
{ \linewidth - 2\sideoffset} > { \box_wd:N  \l_tmpa_box  }
{%TRUE
#2
}
{%FALSE
\tl_set:Nx \l_tmpa_tl { \tl_tail:n { #2 } }
\hbox_set:Nn \l_tmpa_box {  \tl_use:N \l_tmpa_tl }
\dim_while_do:nNnn { \box_wd:N  \l_tmpa_box } >  { \linewidth - 2\sideoffset}
{
\tl_set:Nx \l_tmpa_tl { \tl_tail:N  \l_tmpa_tl  }
\hbox_set:Nn \l_tmpa_box { \tl_use:N  \l_tmpa_tl  }
}
\ldots   \tl_use:N \l_tmpa_tl
}
}
]
{#1}
}
\ExplSyntaxOff

\begin{document}

\begin{minipage}{0.5\linewidth}
\InputCode{\jobname.tex}{http://www.oakfurniturehouse.co.uk/userfiles/image/3B4K1820.jpg}
\end{minipage}

\end{document}

-