![测试列表的外观](https://linux22.com/image/465157/%E6%B5%8B%E8%AF%95%E5%88%97%E8%A1%A8%E7%9A%84%E5%A4%96%E8%A7%82.png)
我想要一个命令\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}