TransWikia.com

How to use optional arguments of the original commands in a macro?

TeX - LaTeX Asked on August 7, 2021

I’d like to use sectioning commands inside macros in order to enhance them, i.e. put some kind of line before and thing after the heading.

Is it possible to use/address the optional arguments of the original commands in the macro, e.g. subsection?

MWE

documentclass[
11pt,
a4paper,
]
{scrartcl}

usepackage{
lmodern,
blindtext
}

usepackage[T1]{fontenc}
usepackage[utf8]{inputenc}

usepackage{
multicol,
xcolor,
}

newcommand{specialheadline}[1]{%
{centering
color{gray}rule{0.9columnwidth}{1pt}color{black}par}
subsection{#1}}

listfiles
begin{document}
begin{center}
Title stuff
end{center}
begin{multicols*}{2}
section{Word}
specialheadline{ASDF}
%specialheadline[123]{ASDF} -- THIS LINE DOES NOT WORK

blindtext[1]
end{multicols*}
end{document}

One Answer

The following definition is probably better since it doesn't require switching back to black, because you could have a different colour preceding specialheadline:

newcommand{specialheadline}[2][]{%
  {centering
  textcolor{gray}{rule{0.9columnwidth}{1pt}}par}
  % How to check if a macro value is empty or will not create text with plain TeX conditionals?
  % https://tex.stackexchange.com/a/53091/5764
  ifrelaxdetokenize{#1}relax
    subsection{#2}%
  else
    subsection[#1]{#2}%
  fi}

It checks whether the optional argument supplied to specialheadline is empty or not and conditions to setting the appropriate sectional unit. You could shorten the explicit conditioning to something like this:

subsection[ifrelaxdetokenize{#1}relax #2else #1fi]{#2}

since the if...fi will be expanded as needed for the ToC.

A more reliable option would be to use xparse's command definition with IfValueTF conditional though:

% usepackage{xparse}% If you have LaTeX2e < 2020-10
NewDocumentCommand{specialheadline}{ o m }{%
  {centering
  textcolor{gray}{rule{0.9columnwidth}{1pt}}par}
  % How to check if a macro value is empty or will not create text with plain TeX conditionals?
  % https://tex.stackexchange.com/a/53091/5764
  subsection[IfValueTF{#1}{#1}{#2}]{#2}}

Correct answer by Werner on August 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP