TransWikia.com

Referring to a custom environment with hyperref

TeX - LaTeX Asked by Thibaut B. on May 17, 2021

I have in my preamble the following code that creates the boxalign* environment, which is a boxed align* environment.

makeatletter  % Code for the boxalign* environment
% newcommandboxalign*autorefname{Box}
@fleqntrue{}
usepackage{empheq}
newenvironment{boxalign*}{@fleqntrueempheq[box=fbox]{align*}}{endempheq}
@fleqnfalse{}
makeatother

However, I want to refer to this box, but hyperref doesn’t recognize the environment and therefore doesn’t create the hyperlink. For instance:

documentclass{article}

usepackage{hyperref}
usepackage{mathtools}

makeatletter  % Code for the boxalign* environment
% newcommandboxalign*autorefname{Box}
@fleqntrue{}
usepackage{empheq}
newenvironment{boxalign*}{@fleqntrueempheq[box=fbox]{align*}}{endempheq}
@fleqnfalse{}
makeatother

begin{document}

begin{boxalign*}label{eq:linear_equation}
    y &= ax + b 
    frac{y - b}{a} &= x
end{boxalign*}

This hyperref[eq:linear_equation]{hyperref} doesn't work.

end{document}

I saw this post that seemed to have an answer to my problem, which is why I tried adding the newcommandboxalign*autorefname{Box} line, but it didn’t work (so I commented it out).

How can I do this?

2 Answers

You could cheat the math environment to let the label command by using another name. You should also set a phantomsection so that there is a destination for the link:

documentclass{article}

usepackage{hyperref}
usepackage{mathtools}

makeatletter  % Code for the boxalign* environment
% newcommandboxalign*autorefname{Box}
@fleqntrue{}
usepackage{empheq}
newenvironment{boxalign*}{@fleqntrueempheq[box=fbox]{align*}phantomsection}{endempheq}
@fleqnfalse{}
makeatother

begin{document}
letmylabellabel

begin{boxalign*}mylabel{eq:linear_equation}
    y &= ax + b 
    frac{y - b}{a} &= x
end{boxalign*}

This hyperref[eq:linear_equation]{hyperref} doesn't work.

end{document}



Correct answer by Ulrike Fischer on May 17, 2021

An alternative to Ulrike Fischer's answer is passing the label as an optional argument.

documentclass{article}

usepackage{mathtools}

makeatletter  % Code for the boxalign* environment
@fleqntrue
usepackage{empheq}
NewDocumentEnvironment{boxalign*}{o}
 {%
  @fleqntrueempheq[box=fbox]{align*}%
  IfValueT{#1}{phantomsection}%
 }
 {%
  endempheq
  IfValueT{#1}{label{#1}}%
 }
@fleqnfalse
makeatother
usepackage{hyperref}

begin{document}

Some text before the alignment
begin{boxalign*}[eq:linear_equation]
    y &= ax + b 
    frac{y - b}{a} &= x
end{boxalign*}

newpage

This hyperref[eq:linear_equation]{hyperref} works.

end{document}

Answered by egreg on May 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP