5

In a current work, i'm using tons of CURIEs (shortened URIs), as common in my community. So i defined a meta-command called \defcurie that i can use to define a prefix like \defcurie{dbr}{http://dbpedia.org/resource/}. It will create a command \dbr in this case that i can later use like \dbr{Dog} to print (and correctly link) dbr:Dog.

Currently when just using \dbr{} it prints dbr:, but i'd like to make it print just dbr (without the trailing :) in case the arg is empty.

MWE:

\documentclass{article}
\usepackage{hyperref}

\newcommand{\curiesize}{\small}
\newcommand{\defcurie}[2]{%
  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize \href{#2##1}{\nolinkurl{#1:##1}}}}%
}
\defcurie{dbr}{http://dbpedia.org/resource/}
\begin{document}
Normal: \dbr{Dog}

Empty: \dbr{}

\end{document}

current output

As you can see in the second line there's a final : that i want to get rid of.

I obviously already tried various things like (each line one attempt, i'll spare you the \noexpand and \expandafter permutations that i ended up trying out of despair):

  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize \href{#2##1}{\nolinkurl{#1\IfStrEq{##1}{}{}{:##1}}}}}%
  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize \href{#2##1}{\nolinkurl{#1\ifthenelse{\isempty{##1}}{}{:##1}}}}}%
  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize \href{#2##1}{\nolinkurl{#1\IfValueT{##1}{:##1}}}}}%

Anything obvious i'm missing?

4

Use \ifblank from etoolbox in order to check the argument ##1 of the internally defined macro.

Alternative: Use \notblank and switch the order of True/False branch

\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref}

\newcommand{\curiesize}{\small}
\newcommand{\defcurie}[2]{%
  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize \href{#2##1}{\nolinkurl{#1\ifblank{##1}{}{:##1}}}}}%
}
\defcurie{dbr}{http://dbpedia.org/resource/}
\begin{document}
Normal: \dbr{Dog}

Empty: \dbr{}

\end{document}
  • Thanks, I guess this is the preferable answer. I slightly modified the original answer by pulling the \ifblank back to reduce code-dup. (Tested to work). – Jörn Hees Oct 15 '17 at 21:31
3

Try this:

\documentclass{article}
\usepackage{hyperref}

\newcommand{\curiesize}{\small}
\makeatletter
\newcommand{\MyIfEmptyF}[1]{%
  \if\relax\detokenize{#1}\relax%
    \expandafter\@gobble%
  \else%
    \expandafter\@firstofone%
  \fi}
\makeatother
\newcommand{\defcurie}[2]{%
  \expandafter\newcommand\csname#1\endcsname[1]{{\curiesize
    \href{#2##1}{\nolinkurl{#1\MyIfEmptyF{##1}{:##1}}}}}%
}
\defcurie{dbr}{http://dbpedia.org/resource/}
\begin{document}
Normal: \dbr{Dog}

Empty: \dbr{}

\end{document}

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.