自动为没有句号的标题添加句号

自动为没有句号的标题添加句号

我尝试将答案调整为如果 '\paragraph' 的参数没有以标点符号结尾,则自动添加最后一个句号在没有句号时自动为标题添加句号。由于我不明白的原因,这个功能无法正常使用。哪里出了问题(见图 3)?

\documentclass{article}

\usepackage{graphicx}
\usepackage{caption}

\DeclareCaptionTextFormat{addpunct}{\maybeaddperiod{#1}}
\captionsetup{textformat=addpunct}


\ExplSyntaxOn
\NewDocumentCommand{\maybeaddperiod}{m}
 {
  \userninefourtwoninethree_maybeaddperiod:n { #1 }
 }

\cs_new_protected:Nn \userninefourtwoninethree_maybeaddperiod:n
 {
  \regex_match:nnTF { .*[\!\?\.\:] \Z } { #1 } { #1 } { #1. }
 }
\ExplSyntaxOff


\begin{document}


\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image}
  \caption{This is an image}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image-a}
  \caption{This is image A}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image-b}
  \caption{This is image B.}
\end{figure}

\end{document}

在此处输入图片描述

答案1

如果您添加\tl_show:n{#1}代码\userninefourtwoninethree_maybeaddperiod:n,您将看到第一个调用显示

> \ignorespaces \caption@makeanchor {This is an image}.

为了其目的,caption将实际的标题文本包装为的参数\caption@makeanchor

你会看到,\maybeaddperiod 绝不以句号结尾,但始终以 结尾}

变成

\cs_new_protected:Nn \userninefourtwoninethree_maybeaddperiod:n
 {
  \regex_match:nnTF { .*[\!\?\.\:] \} \Z } { #1 } { #1 } { #1. }
 }

完整示例:

\documentclass{article}

\usepackage{graphicx}
\usepackage{caption}

\DeclareCaptionTextFormat{addpunct}{\maybeaddperiod{#1}}
\captionsetup{textformat=addpunct}


\ExplSyntaxOn
\NewDocumentCommand{\maybeaddperiod}{m}
 {
  \userninefourtwoninethree_maybeaddperiod:n { #1 }
 }

\cs_new_protected:Nn \userninefourtwoninethree_maybeaddperiod:n
 {
  \regex_match:nnTF { .*[\!\?\.\:] \} \Z } { #1 } { #1 } { #1. }
 }
\ExplSyntaxOff


\begin{document}


\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image}
  \caption{This is an image}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image-a}
  \caption{This is image A}
\end{figure}

\begin{figure}[h]
  \centering
  \includegraphics[height=2cm]{example-image-b}
  \caption{This is image B.}
\end{figure}

\end{document}

在此处输入图片描述

答案2

以下代码显示了如何从宏参数的末尾删除可选的点,然后向输出添加单个句点。所有这些都仅通过 TeX 原始命令完成。

\def\maybeaddperiod #1{\mbaddperiodA #1\empty.\empty\end}
\def\mbaddperiodA #1.\empty #2\end{#1.}

\maybeaddperiod{Text}        % prints: Text.

\maybeaddperiod{Foo. Bar.}   % prints: Foo. Bar.

相关内容