A function that create function with string manipulation
An approach with stringstrings
\documentclass{article}
\usepackage{stringstrings}
\newcommand\aCustomFunction[2]{%
\expandafter\def\csname #1\endcsname{#2}%
\capitalizewords[q]{#1}%
\expandafter\def\csname\thestring\endcsname{\capitalizewords{#2}}%
}
\begin{document}
\aCustomFunction{dog}{cane}
\dog
\Dog
\end{document}
As it is, the above approach reinvokes \capitalizewords
for every instance of \Dog
. That can be avoided in the following way, so that \Dog
literally contains the string "Cane":
\documentclass{article}
\usepackage{stringstrings}
\newcommand\aCustomFunction[2]{%
\expandafter\def\csname #1\endcsname{#2}%
\capitalizewords[q]{#1}%
\edef\tmp{\thestring}%
\capitalizewords[q]{#2}%
\expandafter\edef\csname\tmp\endcsname{\thestring}%
}
\begin{document}
\aCustomFunction{dog}{cane}
\dog
\Dog
\end{document}
Note that either of the approaches will allow indirect syntax such as
\def\blah{this is a test}
\aCustomFunction{cat}{\blah}
\cat
\Cat
However, only the original approach will keep track of things if \blah
is redefined mid-stream.
With expl3
:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\CustomFunction}{mom}
{% #1 = command name, #2 = optional initial, #3 = string
\IfNoValueTF{#2}
{
\verdoja_custom_function:ffff
{ \tl_head:n {#1} } { \tl_tail:n {#1} }
{ \tl_head:n {#3} } { \tl_tail:n {#3} }
}
{
\verdoja_custom_function:ffnn
{ \tl_head:n {#1} } { \tl_tail:n {#1} }
{ #2 } { #3 }
}
}
\cs_new_protected:Nn \verdoja_custom_function:nnnn
{
\tl_new:c { #1 #2 }
\tl_set:cn { #1 #2 }{ #3 #4 }
\tl_new:c { \text_uppercase:n { #1 } #2 }
\tl_set:cx { \text_uppercase:n { #1 } #2 } { \text_uppercase:n { #3 } #4 }
}
\cs_generate_variant:Nn \verdoja_custom_function:nnnn { ff , ffff }
\ExplSyntaxOff
\CustomFunction{dog}{cane}
\CustomFunction{elite}[é]{lite}
\begin{document}
\dog
\Dog
\elite
\Elite
\end{document}
If the first character is special, it's necessary to use the optional character (for compatibility with pdflatex
, in case XeLaTeX or LuaLaTeX is used the optional argument is not required).
Actually, with the recent additions and refinements to expl3
, we can vastly simplify the code.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\CustomFunction}{mm}
{% #1 = command name, #2 = string
\verdoja_custom_function:nn { #1 } { #2 }
}
\cs_new_protected:Nn \verdoja_custom_function:nn
{
\tl_const:cn { #1 } { #2 }
\tl_const:cx { \char_titlecase:N #1 } { \text_titlecase:n { #2 } }
}
\ExplSyntaxOff
\CustomFunction{dog}{cane}
\CustomFunction{elite}{élite}
\begin{document}
\dog
\Dog
\elite
\Elite
\end{document}
We no longer need the initial to be in an optional argument if “special".