%问题:使用自定义命令hh{*}时,如果命令前无字符,则运行报错
%如何解决?
%问答网站:https://ask.latexstudio.net/
%用markdown的格式写代码(三个反引号):code
\documentclass[a4paper]{ctexart}
\RequirePackage{color,xcolor}
\ExplSyntaxOn
\NewDocumentCommand \hh{g}
{\IfNoValueTF {#1}{\,\underline{\hbox to 1cm{}}\,}{\nolinebreak\textcolor[rgb]{1.00,0.00,0.00}{\underline{#1}}}}%-------短横线
\ExplSyntaxOff
\begin{document}
删除这一行汉字会运行出错\hh{123}
\end{document}
自行对比。
原来的作者设计\hh
的时候是没有考虑到这种直接挖空在段首的情况的
\documentclass[a4paper]{ctexart}
\usepackage[showframe]{geometry}
\usepackage{zhlipsum}
\RequirePackage{xcolor}
\NewDocumentCommand\hha{g}%
{\IfNoValueTF{#1}{\,\underline{\hbox to 1cm{}}\,}{\nolinebreak\textcolor[rgb]{1,0,0}{\underline{#1}}}}
\NewDocumentCommand\hhb{g}%
{\IfNoValueTF{#1}{\,\underline{\hbox to 1cm{}}\,}{\textcolor[rgb]{1,0,0}{\underline{#1}}}}
\begin{document}
我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢\hha 你好
我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢\hhb 你好
我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢\hha{我能吞下玻璃而不伤身体}
我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢\hhb{我能吞下玻璃而不伤身体}
%\hha{我能吞下玻璃而不伤身体}我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢%<---报错
\hhb{我能吞下玻璃而不伤身体}我的答案是什么呢我的答案是什么呢我的答案是什么呢我的答案是什么呢
\end{document}
原始代码报错是因为 \nolinebreak
只能在水平模式使用, 而段首是垂直模式.几个注意的点:
\RequirePackage
, 而是 \usepackage
命令;g
参数不推荐使用, 类似的还有 G
, l
, u
;color
和 xcolor
, 单独一个 xcolor
已经足够.修改后的代码如下:
\documentclass[a4paper]{ctexart}
\usepackage{xcolor}
\NewDocumentCommand \hh{m}{%
\IfNoValueTF{#1}{%
\,\underline{\hbox to 1cm{}}\,
}{%
\textcolor[rgb]{1.00,0.00,0.00}{\underline{#1}}%
}%
}
\def\modeCheck{\ifvmode Vmode \else Hmode \fi}
\begin{document}
删除这一行汉字会运行出错\hh{123}
\hh{123}
\modeCheck\modeCheck
\end{document}
运行结果:
后面红色字体超出了边框线,hhb删掉了nolinebreak也没有换行,这种情况可以处理吗
@u4769
\hha
的\nolinebreak
是为了避免出现『横线在第二行行首』的情况,并不是为了处理『答案红色文字换行』的问题,作者似乎也没考虑这一点。详见:https://ask.latexstudio.net/ask/question/17652.html 你可以自行修改
\hh
让其可以换行。另外,对于代码,行内需要使用一对反引号括起来,让其正确高亮。