[Tex/LaTex] Make first word in macro bold

macros

I have the following use-case:

\cmd{cp \opt{r} \marg{from} \marg{to}}

This should typeset a UNIX command for a manual. I’d like the actual command (here, cp) to be typeset in bold while the rest of the command line is typeset normally. Now, I could obviously just write something along the following lines:

\cmd{\textbf{cp} \opt{r} \marg{from} \marg{to}}

… but I’d prefer if this were possible automatically. I thought of two approaches but cannot get either to work:

  1. Make everything bold, cancel bold for nested commands:

    \newcommand*\cmd[1]{%
        \texttt{\textbf{#1}}
    }
    \newcommand*\opt[1]{%
        \undobf{-#1}
    }
    

    … problem: how would \undobf look like? \textrm isn’t appropriate here since I need to preserve the tt style.

  2. Define a TeX command containing a space in its arguments:

    \newcommand*\cmd[1]{%
        \texttt{\setcmd#1}
    }
    \def\setcmd#1 #2{%
        \textbf{#1} #2
    }
    

    But this doesn’t work at all, probably because I’m botching the syntax. But even once the syntax is fixed, this still won’t work for cases where I provide no arguments/options for a command (e.g. \cmd{pwd}).

Best Answer

One could use the usual TeX/LaTeX programming to decide if the first word has something after it and then choose the right branch.

With LaTeX3 functions it's much easier:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tgcursor} % clone of Courier

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\cmd}{ m }
 {
  \krudolph_split_cmd:n { #1 }
 }
\cs_new_protected:Npn \krudolph_split_cmd:n #1
 {
  \seq_set_split:Nnn \l__krudolph_cmd_seq { ~ } { #1 }
  \seq_pop_left:NN \l__krudolph_cmd_seq \l__krudolph_cmd_tl
  \group_begin:
  \normalfont\ttfamily
  \textbf{ \l__krudolph_cmd_tl } ~
  \seq_use:Nnnn \l__krudolph_cmd_seq { ~ } { ~ } { ~ }
  \group_end:
 }
\seq_new:N \l__krudolph_cmd_seq
\tl_new:N \l__krudolph_cmd_tl 
\ExplSyntaxOff

% missing definitions
\newcommand{\opt}[1]{-#1}
\newcommand{\marg}[1]{<#1>}


\begin{document}
\cmd{cp \opt{r} \marg{from} \marg{to}}

\cmd{pwd}
\end{document}

The argument is split at spaces; then the first element is detached for being printed in boldface; the rest is printed in medium weight, separated by spaces.

enter image description here