如何处理宏中的语法错误?

如何处理宏中的语法错误?

我想在日志文件中指出,如果我在行中使用 () 而不是 {} \macro[red,circle]{2/3/a,4/4/b,5/0/c},则会发生错误。最好的方法是什么?

\documentclass{article} 
\usepackage{tikz}

\makeatletter
\def\macro{\pgfutil@ifnextchar[{\macrob}{\macrob[]}}
\def\macrob[#1]#2{%
    \begingroup
       \foreach \ptx/\pty/\name in {#2}{%
       \node[#1] at (\ptx,\pty){\name};}%
    \endgroup
} 
\makeatother

\begin{document}    
 \begin{tikzpicture}
     %\macro[red,circle]{2/3/a,4/4/b,5/0/c}
   \macro[red,circle](2/3/a,4/4/b,5/0/c)
 \end{tikzpicture}    
\end{document}

答案1

如果(使用,它将被吸收为#2

\documentclass{article} 
\usepackage{tikz}

\makeatletter
\def\macro{\pgfutil@ifnextchar[{\macrob}{\macrob[]}}
\def\macrob[#1]#2{%
  \begingroup
  \def\parenthesis@for@err{(}%
  \def\maybe@parenthesis{#2}%
  \ifx\maybe@parenthesis\parenthesis@for@err
    \PackageError{mynicepackage}{You donkey!}{I told you to use {}, not ()}%
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {\absorb@bad@arg}% try and recover somehow
  {\foreach \ptx/\pty/\name in {#2}{%
   \node[#1] at (\ptx,\pty){\name};}%
   \endgroup}%
}
\def\absorb@bad@arg#1){\endgroup}
\makeatother

\begin{document}    

\begin{tikzpicture}
  \macro[red,circle]{2/3/a,4/4/b,5/0/c}
  \macro[red,circle](2/3/a,4/4/b,5/0/c)
\end{tikzpicture}    

\end{document}

这是终端输出:

! Package mynicepackage Error: You donkey!.

See the mynicepackage package documentation for explanation.
Type  H <return>  for immediate help.
 ...                                              

l.28   \macro[red,circle](
                          2/3/a,4/4/b,5/0/c)
? h
I told you to use {}, not ()

答案2

这可能不是最简单或最快的方法,但可以利用该方法来测试可选参数后面\@ifnextchar是否有(但是它不会检查。([])

用于\GenericInfo{...}{...}将一些信息写入日志文件

\documentclass{article} 

\usepackage{tikz}


\begin{document}    

\makeatletter
\def\macro{\@ifnextchar[{\@macroopt}{\@macronoopt}}

\gdef\@temp@{}%
\def\@macroopt[#1]{\gdef\@temp@a{#1}\@macroparen}
\def\@macronoopt{\@macroparen}

\def\@macroparen{\@ifnextchar({%
    \GenericInfo{\macro}{Parenthesis used}
  }{%
    \@macronoparen%
  }%
}

\def\@macronoparen#1{%
  \begingroup
  \foreach \ptx/\pty/\name in {#1}{%
    \expandafter\node\expandafter[\@temp@a] at (\ptx,\pty){\name};}%
  \endgroup
}


\makeatother


\begin{tikzpicture}
  \macro[blue]{2/3/a,4/4/b,5/0/c}
  \macro[red,circle](2/3/a,4/4/b,5/0/c) % Error/Warning message to log
\end{tikzpicture}    


\end{document}

部分内容来自\jobname.log

(/usr/local/texlive/2015/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg

文件:epstopdf-sys.cfg 2010/07/13 v1.3 (r)epstopdf 的配置

对于 TeX Live ))

输入行 35 使用了括号。

相关内容