1

Let's say I want to make a hyperlink like this:

A link is placed \href{www.google.com}{here} to google.

render "A link is placed \href{www.google.com}{here} to google."

Then I decide to make a macro for that:

\newcommand\Myhref[2]{
\href{#1}{#2}
}
A link is placed \Myhref{www.google.com}{here} to google.

render "A link is placed \Myhref{www.google.com}{here} to google."

The spacing is wrong for the second example.

The motivation is that I want to apply a very custom style (with underlines and colouring and font-sizes) that is too complicated for the \hypersetup global style. So I write a macro that applies the style to the hyperlink text. But the spacing is all wrong.

  • 4
    Possible duplicate:What is the use of percent signs (%) at the end of lines?? – moewe Sep 2 '15 at 5:19
  • In this simple case, it suffices to say \let\Myhref\href. But, you probably have a bigger scope. – Werner Sep 2 '15 at 6:26
  • 1
    I do not agree that it is a duplicate. (1) someone searching for an answer to this problem would never find the linked question unless they already know the solution. (2) The linked question does not explain in any way that % signs are a solution to this sort of problem. (3) It isn't obvious why having extra newlines (from the macro definition) should have any effect on spacing, and the linked question does not explain this either. – Matt May 21 '17 at 16:49
3

You are leaving end of line spaces. Put % at the end at two places like

\newcommand\Myhref[2]{%<-------- here
\href{#1}{#2}%        <-------- and here
}

Then you are good to go.

\documentclass{article}
\usepackage{hyperref}
\newcommand\Myhref[2]{%<-------- here
\href{#1}{#2}%        %<-------- and here
}

\begin{document}
  A link is placed \href{www.google.com}{here} to google.

  A link is placed \Myhref{www.google.com}{here} to google.
\end{document}

enter image description here

  • I can see by trying it that this solves the problem, but why does it work? Doesn't the macro simply insert the newlines into the text when the replacement is made? Such newlines wouldn't affect the final spacing. So why does getting rid of the newlines have any effect? – Matt May 21 '17 at 17:07
  • Ah, the answer is that whitespace regions in the source are only reduced to a single space before macro substitutions are done. – Matt May 23 '17 at 12:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.