在 \ref{} 周圍加入 ()

在 \ref{} 周圍加入 ()

我怎麼能添加[]周圍\ref{myref},以便我得到這樣的東西:

[1.1] 

這不起作用:

\documentclass{article}
\usepackage[colorlinks=true,allcolors=blue]{hyperref}
\let\oldref\ref
\renewcommand{\ref}[1]{[\oldref{#1}]}
\begin{document}
\section{Section}
Why cannot include square brackets around cross references? \ref{S}
\subsection{Subsection\label{S}}
This is a subsection.
\end{document}

答:註解掉\usepackage[colorlinks=true,allcolors=blue]{hyperref}就可以了。但我需要hyperref,我不想使用amsmath,而且我不想添加軟體包,因為它們往往會與以後的其他東西發生衝突,例如使用 plastex 等。

答案1

由於hyperref在 後重新定義了事物\begin{document},因此您可以將 推遲renewcommand\AfterBeginDocument

在此輸入影像描述

筆記:

  • 這不適用於帶有星號的變體\ref*

代碼:

\documentclass{article}
\usepackage{letltxmacro}
\usepackage[colorlinks=true,allcolors=blue]{hyperref}

\AtBeginDocument{%
    \LetLtxMacro\oldref{\ref}%
    \DeclareRobustCommand{\ref}[2][]{[\oldref#1{#2}]}%
}

\begin{document}
\section{Section}
Why cannot include square brackets around cross references? \ref{S}
\subsection{Subsection\label{S}}
This is a subsection.
\end{document}

答案2

我正在將我的評論升級為答案,因為它似乎是一個。

不要使用 ,而是\eqref將其放在序言中:

\usepackage{fncylab}
\labelformat{equation}{(#1)}

因此\ref應用於方程式標籤的樣式\eqref與通常情況下的 和 類似,並且在hyperref使用時,連結包含括號。

請注意,雖然您可以將此技術用於其他類型的標籤,但存在一個錯誤,amsthm因此,如果您\newtheorem在表單中使用\newtheorem{<new theorem>}[<old theorem>]{...},則<new theorem>會有字面上地<old theorem>與 、 和fncylab(實際上, )相同的計數器cleverref將對它們進行相同的標記。解決方法是,在定義定理後,您還必須複製它們的計數器:

\usepackage{aliascnt}
\newaliascnt{<new theorem>}{<old theorem>}
\labelformat{<new theorem>}{...}

這將按預期工作。我在我寫的任何東西中都會使用很多計數器來做到這一點。

相關內容