![在环境结束时使用带有可选参数的 includegraphics](https://linux22.com/image/375504/%E5%9C%A8%E7%8E%AF%E5%A2%83%E7%BB%93%E6%9D%9F%E6%97%B6%E4%BD%BF%E7%94%A8%E5%B8%A6%E6%9C%89%E5%8F%AF%E9%80%89%E5%8F%82%E6%95%B0%E7%9A%84%20includegraphics.png)
我正在尝试定义一个环境,该环境调用外部命令根据环境的内容绘制 pdf,并包含输出。
现在我还希望能够将宽度和比例选项传递给\includegraphics
环境结束函数内的宏,但我无法让它以\includegraphics
它仍然可以理解的方式传递参数。
下面的小示例以以下错误结束:
Package keyval Error: scale=1 undefined.
类似地,如果我尝试传递width=0.5\textwidth
到环境,它就会中断:
! Missing \endcsname inserted.
<to be read again>
\textwidth
l.32 \end{haslpicture}
小例子(本例中 cupsfilter 是外部命令)
\documentclass{minimal}
\usepackage{environ}
\usepackage{graphicx}
\newwrite\myOutput
\makeatletter
\def\hasl@writeToFile#1{
\immediate\openout\myOutput=\[email protected]%
\immediate\write\myOutput{#1}%
\immediate\closeout\myOutput%
}
\newenvironment{haslpicture}[2][scale=1]{%
\def\hasl@filename{#2}%
\def\hasl@arguments{#1}%
\newlinechar`\^^M%
\obeylines%
\message{Optional argument: #1}
\Collect@Body\hasl@writeToFile% %macro from the environ package
}{%
\immediate\write18{cupsfilter \[email protected] > \[email protected]}%
\includegraphics[\hasl@arguments]{\[email protected]}
}
\makeatother
\begin{document}
\begin{haslpicture}[scale=1]{xoutput}
one
two
three
\end{haslpicture}
\end{document}
答案1
语法字符=
和,
不得隐藏在键值列表中。通过扩展来修复\hasl@arguments
:
\expandafter\includegraphics\expandafter[\hasl@arguments]{\[email protected]}
答案2
您xparse
也可以在“结束部分”使用这些参数。
\documentclass{article}
\usepackage{xparse}
\usepackage{environ}
\usepackage{graphicx}
\ExplSyntaxOn
\iow_new:N \g_jelmervdl_haslpicture_stream
\cs_new_protected:Nn \jelmervdl_haslpicture_write:n
{
\iow_open:NV \g_jelmervdl_haslpicture_stream \l__jelmervdl_haslpicture_name_tl
\iow_now:Nf \g_jelmervdl_haslpicture_stream { \tl_trim_spaces:n { #1 } }
\iow_close:N \g_jelmervdl_haslpicture_stream
}
\cs_generate_variant:Nn \iow_open:Nn { NV }
\cs_generate_variant:Nn \iow_now:Nn { Nf }
\NewDocumentEnvironment{haslpicture}{O{}m}
{
\tl_set:Nn \l__jelmervdl_haslpicture_name_tl { #2.txt }
\endlinechar=`\^^J \scan_stop:
\use:c { Collect@Body } \jelmervdl_haslpicture_write:n
}
{
\message{Optional~argument:~#1}
\sys_shell_now:n { cupsfilter ~ #2.txt ~ > ~ #2.pdf }
\includegraphics[#1]{#2.pdf}
}
\ExplSyntaxOff
\begin{document}
\begin{haslpicture}[scale=1]{xoutput}
one
two
three
\end{haslpicture}
\end{document}
与其玩弄\obeylines
,不如将其设置\endlinechar
为^^J
,这是 LaTeX 中默认的换行符。