Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Here is my MWE, I want to 'refactor' the code so that I do not need to write so much when I import source code into my document:

\documentclass[12pt,a4paper]{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{wrapfig}
\usepackage{lipsum}

\begin{document}

\begin{wrapfigure}{r}{0.5\textwidth}
  \begin{center}
    \includegraphics[width=0.6\textwidth]{foo}
  \end{center}
  \caption{The foo describes the bar}
  \label{img:foo}
\end{wrapfigure}

\lipsum

\end{document}

Ideally I would prefer to just do:

\begin{mygraphic}{r}{0.5\textwidth}{The foo describes the bar}{img:foo}
    \includegraphics[width=0.6\textwidth]{foo}
\end{mygraphic}

I assume I need to do something like:

\makeatletter
\newenvironment{mygraphic}[4]
{%begin part
\begin{wrapfigure}{#1}{#2}
  \begin{center}
}
{%end part
  \end{center}
  \caption{#3}
  \label{#4}
\end{wrapfigure}}
\makeatother

However that doesn't work. It complains about caption and label parameters, so I moved those up into the begin part but that didn't work.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

Your definition doesn't work because you cannot use parameters in the "ending part" of the definition of a new environment; see Why can't the end code of an environment contain an argument?. Known workarounds include using macros to store the parameters in the "beginning part" of the definition, or using the environ package or using the xparse package.

In this particular case, taking into account this warning mentioned in the documentation of wrapfig:

If you put a wrapfigure in a parbox or a minipage, or any other type of grouping, the text wrapping should end before the group does.

it seems a better idea to define a command instead of an environment; something along these lines:

\documentclass[12pt,a4paper]{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{wrapfig}
\usepackage{lipsum}

% syntax: \mygraphic[options for \includegraphics]{position}{width}{name}{caption}{label}
\newcommand\mygraphic[6][]{%
   \begin{wrapfigure}{#2}{#3}
   \centering\includegraphics[#1]{#4}
   \caption{#5}\label{#6}\end{wrapfigure}}

\begin{document}

\mygraphic[width=.6\linewidth]{r}{0.5\textwidth}{foo}{The foo describes the bar}{img:test}

\lipsum[1-7]

\end{document}

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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