0

I construct a macro to give text a feature of opacity with \pgfsetfillopacity from tikz. It works all right except that when the second argument contains \par which causes the .tex file fail to compile. Why and how to fix it?

\documentclass{article}
\usepackage{geometry,tikz,xparse}
\geometry{showframe}

\NewDocumentCommand{\opacity}{g g}{%
    \IfNoValueTF{#2}
      {\IfNoValueTF{#1}
        {\pgfsetfillopacity{1}}
        {\pgfsetfillopacity{#1}}
      }%
      {\pgfsetfillopacity{#1}#2\pgfsetfillopacity{1}}%
}

\begin{document}
\opacity{0.5}{some text\par some text some text some text some text some text some text some text some text some text \\some text}

\end{document}
5
  • 2
    Try \NewDocumentCommand{\opacity}{g +g}. P.S.: Don't use g :) Commented Jun 18, 2021 at 1:25
  • Perfect solution! Thank you! And is there a way to use \long in the common Latex \newcommand
    – lyl
    Commented Jun 18, 2021 at 1:32
  • 1
    \newcommand creates \long commands by default: you actually have to use \newcommand* to create non-\long commands. But with \newcommand you have all arguments \long, or none \long. You could use \NewDocumentCommand{\opacity}{m +m} to have xparse and avoid g (in case you don't know, m is a mandatory argument, and g is an optional argument delimited by {...}: a really bad idea :). Commented Jun 18, 2021 at 1:41
  • 1
    @lyl \newcommand is \long already. If you want to avoid \long, use \newcommand*. Commented Jun 18, 2021 at 1:41
  • Thank you all so much for these good information and suggestions!
    – lyl
    Commented Jun 18, 2021 at 1:44

1 Answer 1

3

Phelype's suggestion of using {g +g} is just too easy a way to fix the problem. Since I often reinvent the wheel for fun, here is a way to search through the argument for \par and apply \opacity to each paragraph-length section of the input. I call it \oparcity, to consummate the PhARce.

\documentclass{article}
\usepackage{geometry,tikz,xparse}
\geometry{showframe}

\NewDocumentCommand{\opacity}{g g}{%
    \IfNoValueTF{#2}
      {\IfNoValueTF{#1}
        {\pgfsetfillopacity{1}}
        {\pgfsetfillopacity{#1}}
      }%
      {\pgfsetfillopacity{#1}#2\pgfsetfillopacity{1}}%
}

\long\def\oparcity#1#2{\iftrue\def\opvalue{#1}\oppar#2\par\fi}
\long\def\oppar#1\par#2\fi{\fi
  \opacity{\opvalue}{#1}\ifx\relax#2\relax\else\par\oppar#2\fi}

\begin{document}
\oparcity{0.5}{some text\par some text some text some text 
some text some text some text some\\ 
text some text some text \\some text}
\end{document}

enter image description here

2
  • Why, oh why? ;-) Commented Jun 18, 2021 at 1:37
  • @PhelypeOleinik Because I still have not mastered \NewDocumentCommand syntax Commented Jun 18, 2021 at 1:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .