3

I'm trying to write my own command that wraps the \VerbatimInput command. I'd like my command to take optional arguments (those given inside [...]) and pass those directly to \VerbatimInput[...]. Of course, if the optional arguments to my command are not given, then nothing should be passed to \VerbatimInput.

How can I do this? I'm a relative novice to creating custom commands in LaTeX.

  • see tex.stackexchange.com/questions/308/… – user36296 Feb 13 '17 at 22:37
  • 1
    This mostly depends on what “wrapping” you're doing. But I guess that \newcommand{\foo}[2][]{...\VerbatimInput[#1]{#2}...} should do. – egreg Feb 13 '17 at 22:38
  • 1
    Use New Renew and DeclareDocumentCommand as Christian Hupfer suggested. – MaestroGlanz Feb 13 '17 at 23:08
2

If a macro argument is supposed to be a set of key-value pairs, making use of standard packages to the purpose (keyval, xkeyval and others), it is generally harmless to pass it the empty list.

So

\newcommand{\foo}[2][]{%
  <actions to be performed before>%
  \VerbatimInput[#1]{#2}%
  <actions to be performed after>%
}

is the method you're looking for, because fancyvrb does use keyval.

8

egreg provided the easiest way with \newcommand{\foo}[2][]{\VerbatimInput[#1]{#2}}, here's the xparse way with \NewDocumentCommand and checking with \IfValueTF{#1} whether the optional (o) argument is given or not.

If more optional arguments are desired, it is definitely easier with \NewDocumentCommand.

\documentclass{article}

\usepackage{xparse}
\usepackage{fancyvrb}

\begin{filecontents}{helloworldexample.c}
 #include<stdio.h>

int main(int argc,char **argv)
{
  printf("Hello World!\n");
  return(0);
}
\end{filecontents}
\NewDocumentCommand{\myverb}{om}{%
  \IfValueTF{#1}{%
    \VerbatimInput[{#1}]{#2}%
  }{%
    \VerbatimInput{#2}%
  }%
}

\begin{document}
\myverb{helloworldexample.c}

\myverb[frame=single,numbers=left]{helloworldexample.c}
\end{document}
  • Generally, if a command accepts an optional argument consisting of a list of “key=value” items, it does not balk if it is passed an empty list. – egreg Feb 13 '17 at 22:56
  • @egreg: True. But this is on the safe side for other occasions, where there is no such key-value interface lurking behind the optional argument. – user31729 Feb 13 '17 at 23:09
  • @egreg In the general case, the default value for the optional argument can be non-empty regardless whether the optional argument is intended for key-value pairs. – Heiko Oberdiek Feb 13 '17 at 23:28
  • @ChristianHupfer [{#1}] allows square brackets inside #1. – Heiko Oberdiek Feb 13 '17 at 23:30
  • @HeikoOberdiek: Thanks, I've added your suggestion. – user31729 Feb 13 '17 at 23:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.