Hyperref: `\hypersetup` 被 `\AtBeginDocument` 忽略

Hyperref: `\hypersetup` 被 `\AtBeginDocument` 忽略

我想向类添加一个选项,该选项会自动加载通过命令提供的text.cls默认样式。这按预期工作。hyperrefhypersetup

然而,如果我想解释一下非官方的hyperref 应该是你最后加载的包规则,参见超链接文档hyperref,并移动里面的加载\AtBeginDocument似乎hypersetup被忽略了,我收到了几个警告,比如

Package hyperref Warning: Option `colorlinks' has already been used,
(hyperref)                setting the option has no effect on input line 9.

这是为什么?我该如何解决?


班级

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{text}[2019/11/25 A documentation class]

% ---------------------------
% Package
% ---------------------------

\RequirePackage{kvoptions}
\RequirePackage{ifthen}

% ---------------------------
% Options
% ---------------------------

\SetupKeyvalOptions{%
  family=text,%
  prefix=text@,%
  setkeys=\kvsetkeys,%
}

% Bool option
\DeclareBoolOption[false] {hyperref}

\DeclareDefaultOption{%
  \PassOptionsToClass{\CurrentOption}{report}%
}

% Process options
\ProcessKeyvalOptions{text}

\LoadClass{report}

% ---------------------------
% Package
% ---------------------------

\iftext@hyperref
  \AtBeginDocument{
    \PassOptionsToPackage{%
      bookmarks = true,
      pdfusetitle,%
    }{hyperref}
    %
    \RequirePackage{hyperref}
    %
    \hypersetup{%
      colorlinks    = true,%  Color text instead of boxes
      linkcolor     = black,% Color of internal links
      citecolor     = black,% Color of citations
      urlcolor      = blue,%  Color of external urls
      pdfstartview  = Fit,%
      pdfmenubar    = true,%
      pdftoolbar    = true,%
      bookmarksopen = false,%
      %bookmarksopenlevel = 1,%
    }
  }
\fi

% ---------------------------
% Fin
% ---------------------------

\endinput

平均能量损失

\documentclass[%
  hyperref=true,
]{text}

\author{An author}
\title{text class description}
\date{\today}

\begin{document}

\chapter{Test}
\label{sec:test}

Hello World! Reference to \autoref{sec:test}. And a URL:

\href{https://tex.stackexchange.com}{https://tex.stackexchange.com}

\end{document}

结果

  • 没有AtBeginDocument(想要)

在此处输入图片描述

  • AtBeginDocument

在此处输入图片描述

答案1

最好\AtEndPreamble从 etoolbox 包中加载 hyperref。但基本上在类中加载 hyperref 有点麻烦,因为还有一些包应该稍后加载(cleveref)、强制提前加载 hyperref 的包(pdfx)、尝试检测 hyperref 的包等等。

\documentclass{book}
\usepackage{etoolbox}
%\AtBeginDocument{%
\AtEndPreamble{%
\RequirePackage{hyperref}
\hypersetup{%
      colorlinks    = true,%  Color text instead of boxes
      linkcolor     = black,% Color of internal links
      citecolor     = black,% Color of citations
      urlcolor      = blue,%  Color of external urls
      pdfstartview  = Fit,%
      pdfmenubar    = true,%
      pdftoolbar    = true,%
      bookmarksopen = false,%
      %bookmarksopenlevel = 1,%
    }}

\begin{document}


\chapter{Test}
\label{sec:test}

Hello World! Reference to \autoref{sec:test}. And a URL:

\href{https://tex.stackexchange.com}{https://tex.stackexchange.com}

\end{document}

相关内容