将 soul:hl 函数转变为环境

将 soul:hl 函数转变为环境

hl我正在使用包中的函数soul来突出显示文本。我想创建一个特定的环境,用于突出显示。我尝试过newenvironment,但没有弄清楚如何正确使用(另请参阅此邮政)。我也尝试使用该包environ来定义一个新的环境,但现在面临来自 soul 的错误消息:软件包 soul 错误:重建失败。我遇到了用组括号括起来的可连字符材料,我无法处理。请删除括号或使用 \mbox (\hbox) 使材料不可拆分。

我知道如何嵌入hl到环境中吗?

谢谢!

\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}


\usepackage{environ}
\usepackage{color,soul}
\NewEnviron{newtext}{\hl{\BODY}}
%\NewEnviron{newtext}{\BODY}

\begin{document}


\hl{I work well when called  as a function }

\begin{newtext} I don't seem to work when called as an enviornment. \end{newtext}


\end{document}

答案1

您需要在吸收它\BODY之前进行扩展\hl。执行此操作的方法是使用\expandafter,它会跳过一个标记并(一次)扩展下一个标记,然后再执行跳过的标记。由于\BODY是 前面的两个标记\hl,中间有一个左括号,因此还必须在 之前{包含一个,以便第一个将扩展第二个,而第二个又将跳过并扩展。\expandafter{\expandafter\expandafter{\BODY

\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}


\usepackage{environ}
\usepackage{color,soul}
\NewEnviron{newtext}{\expandafter\hl\expandafter{\BODY}}
%\NewEnviron{newtext}{\BODY}

\begin{document}


\hl{I work well when called  as a function }

\begin{newtext} I don't seem to work when called as an enviornment. \end{newtext}


\end{document}

在此处输入图片描述

答案2

expl3 版本:

hl 解释3

使用环境选项来改变颜色。

平均能量损失

\documentclass{article}
\usepackage{xparse} %part of kernel now
\usepackage{xcolor,soul}
\ExplSyntaxOn
\NewDocumentEnvironment { newtext } { o +b } {
    \IfNoValueF {#1}
     {      
        \sethlcolor{#1}
        }
    \hl { #2 } 
}{}

\ExplSyntaxOff


\begin{document}


\hl{I work well when called  as a function }

\begin{newtext} 
I don't seem to work when called as an environment.

I don't seem to work when called as an environment.

I don't seem to work when called as an environment.

\end{newtext}

---

\begin{newtext}[green]
I don't seem to work when called as an environment.

I don't seem to work when called as an environment.

I don't seem to work when called as an environment.

\end{newtext}


\end{document}

答案3

如果您愿意使用 LuaLaTeX,您可以使用我的lua-ul包来避免必须environ一起使用和朋友,而是定义一个“常规”环境。然后对可能的参数的限制也更少:

\documentclass{article}
\usepackage{xcolor,luacolor,lua-ul}
\makeatletter
\newenvironment{newtext}[1][yellow] {%
   \luaul@setcolor{#1}%
   \@highLight
}{}
\makeatother

\begin{document}


\highLight{I work well when called  as a function }

\begin{newtext} 
I work well when called as an environment.

I work well when called as an environment.

I work well when called as an environment.

\end{newtext}

---

\begin{newtext}[green]
I work well when called as an environment.

I work well when called as an environment.

I work well when called as an environment.

Even allows using e.g.\@ \verb|\verb| when used as an environment.
\end{newtext}


\end{document}

上述代码的输出表明突出显示有效

相关内容