kvoptions 中字符串值的使用

kvoptions 中字符串值的使用

我跟着例子Heiko 非常出色地解释了他处理我的请求的方法。由于我的主要想法是同时设置一个副标题,所以我有点困惑为什么没有设置“副标题”——或者更确切地说:我不知道如何正确访问它以进行打印。

\documentclass{article}
\usepackage{keyval}
\usepackage{kvoptions}

\SetupKeyvalOptions{
    family=mosquito,
    prefix=mosquito@,
}

\makeatletter
\DeclareBoolOption{hideInToC}
\DeclareStringOption{subtitle}

\newcommand\sectionLvl[3][]{%
    \begingroup
    \setkeys{mosquito}{#1}%
    \ifcase#2\relax  % 0 = chapter
    \def\tmp@mosquito{\chapter}%
    \or  % 1 = section
    \ifmosquito@hideInToC
    \def\tmp@mosquito{\section*}%
    \else
    \def\tmp@mosquito{\section}%
    \fi
    \else  % subsection
    \def\tmp@mosquito{\subsection}%
    \fi
    \expandafter\endgroup
    \tmp@mosquito{#3}{
        {sub: \mosquito@subtitle}
}
}%
\makeatother

\begin{document}
    \tableofcontents
    
    \bigskip
    \hrule
    
    \sectionLvl[subtitle={Test Subtitle}]{1}{Title 1 (shown)}
    \sectionLvl[hideInToC]{1}{Title 2 (hideInToC)}
    \sectionLvl[subtitle={Test Subtitle2}]{1}{Title 3 (shown)}
    \sectionLvl{2}{SubTitle 4 (shown)}
\end{document}

自从我从 ˋkeyvalˋ 切换到 ˋkvoptionsˋ 后,我想知道主要的区别是什么。我知道语法不同,但在性能方面(通过 LuaHBTex 使用时)或更好的稳健性方面有这样或那样的好处?

答案1

\setkeys在组内调用以保持设置本地化。在结束组之前 ,\tmp@mosquito通过 进行扩展。但是,通过 重置为空字符串。因此,您需要一个更复杂的版本。以下代码将 保持在组外,但在结束组之前扩展和。中标题的未知标记受到 的硬扩展保护。我不清楚副标题应该放在哪里,在章节/部分标题之后还是内部。该示例使用更困难的内部版本。\expandafter\endgroup\tmp@mosquito\mosquito@subtitle\endgroup\chapter\section\tmp@mosquito\mosquito@subtitle#3\edef\unexpanded

\documentclass{article}
\usepackage{keyval}
\usepackage{kvoptions}

\SetupKeyvalOptions{
    family=mosquito,
    prefix=mosquito@,
}

\makeatletter
\DeclareBoolOption{hideInToC}
\DeclareStringOption{subtitle}

\newcommand\sectionLvl[3][]{%
    \begingroup
    \setkeys{mosquito}{#1}%
    \ifcase#2\relax  % 0 = chapter
    \def\tmp@mosquito{\chapter}%
    \or  % 1 = section
    \ifmosquito@hideInToC
    \def\tmp@mosquito{\section*}%
    \else
    \def\tmp@mosquito{\section}%
    \fi
    \else  % subsection
    \def\tmp@mosquito{\subsection}%
    \fi
    \edef\x{%
      \endgroup
      \expandafter\noexpand\tmp@mosquito{%
        \unexpanded{#3}%
        \ifx\mosquito@subtitle\@empty
        \else
          \space(sub: \unexpanded\expandafter{\mosquito@subtitle})%
        \fi
      }%
    }%
    \x
}%
\makeatother

\begin{document}
    \tableofcontents

    \bigskip
    \hrule

    \sectionLvl[subtitle={Test Subtitle}]{1}{Title 1 (shown)}
    \sectionLvl[hideInToC]{1}{Title 2 (hideInToC)}
    \sectionLvl[subtitle={Test Subtitle2}]{1}{Title 3 (shown)}
    \sectionLvl{2}{SubTitle 4 (shown)}
\end{document}

相关内容