How to create your own commands in Latex using \newcommand

By Alvin J. Alexander, devdaily.com

Here is an example Latex file where I'm experimenting with various newcommand and renewcommand capabilities. The file actually contains six examples, and in each step I add one more Latex feature that is a little harder than the previous step. In the last several examples I start passing parameters into my commands. After that, I start using the "html" package (html.sty) and the "ifthen" package (ifthen.sty) to do some decision-making in my last several newcommand/renewcommand examples.

Without any further ado, here is the sample Latex code:

\documentclass[a4paper,11pt]{article}
\author{Al Alexander}
\title{}

\usepackage{html}
\usepackage{ifthen}

\begin{document}

%-----------------------------------------
% (1) a simple test to get started.
%     replace the "enumerate" environments
%     begin/end tags with our own
%     commands.
%-----------------------------------------

\newcommand{\be}{\begin{enumerate}}
\newcommand{\ee}{\end{enumerate}}

% now use the new command
\be
  \item Item 1
  \item Item 2
\ee

%-----------------------------------------
% (2) Create a new command named "\atest"
%     and just use it to replace some text.
%     Start fooling around to make the 
%     syntax more readable.
%-----------------------------------------

\newcommand{\atest}
{
 and seven years ago
}

Lincoln said "Four score \atest"

%---------------------------------------
% (3) renew/re-use the same command name
%---------------------------------------
\renewcommand{\atest}
{
 our fathers set forth
}

\atest

%---------------------------------------
% (4) pass in an argument now. start
%     getting ready to do what I really
%     want to do, which is to accept an
%     argument and make a decision about
%     what to print. note that the "<"
%     and ">" symbols don't really print
%     right with pdflatex, but that's not
%     what I'm after in the long run, so
%     it's no big deal.
%---------------------------------------
\renewcommand{\atest}[1]
{
IMAGE: <img src="{#1}" border="0">
}

\atest{images/test.jpg}

%---------------------------------------
% (5) Same thing, but use the html pkg
%     to make a decision.
%---------------------------------------
\renewcommand{\atest}[1]
{
\latex{HTML PKG: Do the Latex thing to include this image: {#1}}
\html{HTML PKG: <img src="{#1}" border="0">}
}

\atest{images/test.jpg}

%---------------------------------------
% (6) Similar, but use the ithen pkg
%     to make a decision.
%---------------------------------------
\renewcommand{\atest}[2]
{
  \ifthenelse{\equal{#1}{html}}{IFTHEN: <img src="{#2}" border="0">}{}
  \ifthenelse{\equal{#1}{pdf}}{IFTHEN: Do the Latex thing: {#2}}{}
}

\atest{html}{images/test.jpg}

\end{document}


devdaily logo