\sbox 来自环境内部
我正在尝试在环境中保存一些文本以供以后使用。我能想到的最小的测试用例是这样的。环境关闭后,sbox
中保存的文本将不可用。我该如何解决这个问题?谢谢。
\documentclass{article}
\begin{document}
\newsavebox{\somebox}
\begin{itemize}
\item hello1
\item hello1 \sbox{\somebox}{Some text}
\end{itemize}
This should show something, but does not: "\usebox{\somebox}"
\end{document}
I'm trying to save some text inside an environment for later use. The smallest test case I could come up with is this. The saved text in the sbox
isn't available after the environment is closed. How can I work around that? Thanks.
\documentclass{article}
\begin{document}
\newsavebox{\somebox}
\begin{itemize}
\item hello1
\item hello1 \sbox{\somebox}{Some text}
\end{itemize}
This should show something, but does not: "\usebox{\somebox}"
\end{document}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想我可以通过使用
\def
来解决这个问题。像这样:\documentclass{article}
\开始{文档}
\开始{逐项列出}
\项目你好1
\项目你好1
\global \def \somebox {一些文本}
\end{逐项列出}
这应该显示一些内容: \somebox
\结束{文档}
I think I can work around this by using
\def
. like so:\documentclass{article}
\begin{document}
\begin{itemize}
\item hello1
\item hello1
\global \def \somebox {Some text}
\end{itemize}
This should show something: \somebox
\end{document}
您在这里遇到的是范围界定问题。在 (La)TeX 中,您可以使用
{ ... }
、\bgroup ... \egroup
或\begingroup ... \endgroup 引入作用域
。前两者大致相同,\bgroup
和\egroup
分别由\let\bgroup{
和\let\定义egroup}
;最后一个略有不同。但作用域属性是相同的:在这些作用域内创建或修改的任何命令、boxen 等在外部都不可见。在 LaTeX 中,所有环境\begin{env} ... \end{env}
都将其内容隐式包装在\begingroup ... \endgroup
中。这意味着您的\sbox{\somebox}{Some text}
修改仅在\end{itemize}
之前可见;之后,修改将被撤消。要解决此问题,请在前面添加任何命令,例如\newcommand
、\def
、\newsavebox
、\sbox
等.,使用\global
,强制定义在全局范围内进行,并且在任何地方都可见。另外,要在 (La)TeX 中使用引号,请编写
``双引号''
、``双引号'
或`单引号'
>;"
字符仅用于结束引号,而不是开始引号。将所有这些放在一起即可得到修改后的片段What you're running into here is a scoping issue. In (La)TeX, you can introduce scopes with
{ ... }
,\bgroup ... \egroup
, or\begingroup ... \endgroup
. The former two are roughly the same, as\bgroup
and\egroup
are defined by\let\bgroup{
and\let\egroup}
; the last one is slightly different. But the scoping property is the same: any commands, boxen, etc., created or modified within those scopes are not visible outside. And in LaTeX, all environments\begin{env} ... \end{env}
implicitly wrap their contents in\begingroup ... \endgroup
. This means that your\sbox{\somebox}{Some text}
modification is only visible until the\end{itemize}
; after that, the modification is undone. To get around this, prepend any command like\newcommand
,\def
,\newsavebox
,\sbox
, etc., with\global
, which forces the definition to take place at the global scope and be visible everywhere.Also, to use quotes in (La)TeX, write
``double quoted''
,``double quoted"
, or`single quoted'
; the"
character is only for closing quotes, not opening quotes. Putting this all together gives you the revised snippet