测试列表的外观

测试列表的外观

我想要一个命令\myInclude{}执行以下操作:

  • \myInclude{}不执行任何操作(如果参数为空)
  • \myInclude{file.tex}file.tex如果先前没有包含过该文件(通过命令),则包含该文件\myInclude{file.tex};否则,它不执行任何操作。

你能帮助我吗?

答案1

这是一个依赖 TeX 的解决方案\ifcsname

\newcommand\myIncludeSeen[1]{%
  \expandafter\newcommand\csname myInclude:#1\endcsname{}%
}
\newcommand\myInclude[1]{%
  \ifcsname myInclude:#1\endcsname
  \else
    \myIncludeSeen{#1}%
    \input{#1}%
  \fi
}
\myIncludeSeen{}

与@egreg 的解决方案不同,它不会.tex自动附加,因此\myInclude{file}\myInclude{file.tex}被视为加载不同的文件。 在此处输入图片描述


\documentclass{article}
\newcommand\myIncludeSeen[1]{%
  \expandafter\newcommand\csname myInclude:#1\endcsname{}%
}
\newcommand\myInclude[1]{%
  \ifcsname myInclude:#1\endcsname
  \else
    \myIncludeSeen{#1}%
    \input{#1}%
  \fi
}
\myIncludeSeen{}

\begin{filecontents*}{colas-a.tex}
This is file A
\end{filecontents*}
\begin{filecontents*}{colas-b.tex}
This is file B
\end{filecontents*}

\begin{document}

Trying to include A

\myInclude{colas-a}

Trying to include nothing

\myInclude{}

Trying to include B

\myInclude{colas-b}

Trying to include A

\myInclude{colas-a}

Trying to include B

\myInclude{colas-b}

End

\end{document}

答案2

您可以填充一个序列并检查文件名是否存在。

.tex如果不存在,我也会添加扩展(并使用\input而不是\include)。

\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\myInclude}{m}
 {
  \IfBlankF{#1}{ \colas_myinclude:n { #1 } }
 }

\cs_new_protected:Nn \colas_myinclude:n
 {
  \str_if_eq:eeTF { \str_range:nnn { #1 } { -4 } { -1 } } { .tex }
   {
    \__colas_myinclude:n { #1 }
   }
   {
    \__colas_myinclude:n { #1.tex }
   }
 }

\seq_new:N \g_colas_myinclude_prop

\cs_new_protected:Nn \__colas_myinclude:n
 {
  \seq_if_in:NnF \g_colas_myinclude_prop { #1 }
   {
    \seq_gput_right:Nn \g_colas_myinclude_prop { #1 }
    \input{#1}
   }
 }

\ExplSyntaxOff

\begin{filecontents*}{colas-a.tex}
This is file A
\end{filecontents*}
\begin{filecontents*}{colas-b.tex}
This is file B
\end{filecontents*}

\begin{document}

Trying to include A

\myInclude{colas-a}

Trying to include nothing

\myInclude{}

Trying to include B

\myInclude{colas-b.tex}

Trying to include A

\myInclude{colas-a.tex}

Trying to include B

\myInclude{colas-b}

End

\end{document}

在此处输入图片描述

相关内容