自定义下划线命令来输出填空题答案,当命令前无字符时运行出错

发布于 2025-04-17 16:44:11

%问题:使用自定义命令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}

查看更多

关注者
0
被浏览
168
Sagittarius Rover
我要成为Typst糕手/(ㄒoㄒ)/~~

自行对比。

原来的作者设计\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}

image.png

2 个回答
Eureka
Eureka 1天前
这家伙很懒,什么也没写!

原始代码报错是因为 \nolinebreak 只能在水平模式使用, 而段首是垂直模式.几个注意的点:

  • 并不需要启用 expl3 环境;
  • 普通用户在导言区一般不使用 \RequirePackage, 而是 \usepackage 命令;
  • 在如今, g 参数不推荐使用, 类似的还有 G, l, u;
  • 不需要同时加载 colorxcolor, 单独一个 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}

运行结果:
image.png

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览