renewcommand 中的 xstring 命令

renewcommand 中的 xstring 命令

我正在尝试\texttt以结束.或为条件更新命令,。但是在执行此操作后:

\usepackage{xstring}

\let\OldTexttt\texttt
\renewcommand{\texttt}[1]{%
    \OldTexttt{\hspace{0.4em}#1}%
    \IfEndWith{#1}{.}{}{\hspace{0.4em}}%    
}

编辑:不起作用的示例。

\documentclass{article}

\usepackage{xstring}

\let\OldTexttt\texttt
\renewcommand{\texttt}[1]{%
    \OldTexttt{\hspace{0.4em}#1}%
    \IfEndWith{#1}{.}{}{\hspace{0.4em}}%
    \IfEndWith{#1}{,}{}{\hspace{0.4em}}%    
}


\begin{document}

\section{This is \texttt{section.}}
bbbb 
\texttt{test}
\texttt{section.}
\texttt{section,}
\texttt{test}
aaa

\end{document}

错误:

! Argument of \@sect has an extra }.
<inserted text> 
                \par 
l.18 \section{This is \texttt{section.}}

? 
! Emergency stop.
<inserted text> 
                \par 
l.18 \section{This is \texttt{section.}}

有人能帮忙解决什么问题吗?

答案1

这里有一个解决方案尝试expl3

\documentclass[]{article}
\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage{letltxmacro}

\LetLtxMacro\OldTexttt\texttt

\usepackage{xparse}
\ExplSyntaxOn
\cs_new:Npn \petr_extract_lasttoken:n #1
  {
   \tl_head:f { \tl_reverse:n { #1 } }
 }
\cs_generate_variant:Nn \tl_if_eq:nnF {xnF}

\DeclareDocumentCommand \texttt { m }
 {
  \hspace*{0.4cm}
  \OldTexttt{ #1 }
  \tl_if_eq:xnF  { \petr_extract_lasttoken:n {#1}  } { . } {\hspace*{0.4cm}}
 }
\ExplSyntaxOff
\begin{document}


foo \texttt{bar} foo

foo \texttt{bar.} foo

\section{This is \texttt{section.}}
bbbb 
\texttt{test}
\texttt{section.}
\texttt{section,}
\texttt{test}
aaa
\end{document}

答案2

重新定义\texttt并不健壮。这可以通过使用\DeclareRobustCommand并使用letltxmacro处理原始健壮的 LaTeX 内部的包来实现\texttt

\documentclass{article}

\usepackage{xstring}
\usepackage{letltxmacro}

\LetLtxMacro\OldTexttt\texttt
\DeclareRobustCommand*{\texttt}[1]{%
    \OldTexttt{\hspace{0.4em}#1}%
    \IfEndWith{#1}{.}{}{%
      \IfEndWith{#1}{,}{}{\hspace{0.4em}}%
    }%
}

\begin{document}

\section{This is \texttt{section.}}
bbbb
[\texttt{test}]
[\texttt{section.}]
[\texttt{section,}]
[\texttt{test}]
aaa

\end{document}

结果

更新:此外,宏中的逻辑也已修复,0.4em如果字符串不以. 或者 ,

答案3

这是 的工作l3regex!当然,仍然应该\texttt使用 来保存\LetLtxMacro。但是,我不会使用\hspace*:额外的空间应该在换行符处消失。

\documentclass{article}
\usepackage[T1]{fontenc}

\usepackage{letltxmacro,xparse,l3regex}
\LetLtxMacro\latextexttt\texttt

\ExplSyntaxOn
\DeclareDocumentCommand \texttt { m }
 {
  \petr_spaced_texttt:n { #1 }
 }
\cs_new_protected:Npn \petr_spaced_texttt:n #1
 {
  \hspace{0.4em}
  \latextexttt{ #1 }
  % Check if the string ends with a period or a comma
  % \Z matches the end of the string
  \regex_match:nnF { (\.|\,) \Z } { #1 } { \hspace{0.4em} }
 }
\ExplSyntaxOff
\begin{document}
\tableofcontents

\section{This is |\texttt{section.}|}
bbbb 
|\texttt{test}|
|\texttt{section.}|
|\texttt{section,}|
|\texttt{test}|
aaa
\end{document}

在此处输入图片描述

相关内容