环境中的参数

环境中的参数

我正在尝试创建一个环境。错误如下,传递的参数与单词 Theorem 不在同一行。下面代码的结果是

定理 1.1.1[

期望的结果是

定理 1.1.1 (我这样做)

\documentclass[a4paper,12pt]{book}  
\usepackage[top=3cm,bottom=3.5cm,left=3cm,right=2cm]{geometry}
\usepackage[brazil]{babel}
\usepackage[utf8]{inputenc} 
\usepackage{lipsum}
\usepackage{xcolor}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%  ENVIROMENTS  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage{framed}

\renewenvironment{leftbar}[2][\hsize]
{
    \def\FrameCommand
    {
        {\color{#2}\vrule width 3pt}
        \hspace{1pt}
    }
    \MakeFramed{\hsize#1\advance\hsize-\width\FrameRestore}
}
{\endMakeFramed}

%%%%%%%%%%%%%%% ENVIROMENT THEOREM  %%%%%%%%%%%%

\newcounter{myteocounter}
\counterwithin{myteocounter}{section}

\newenvironment{myteo}[1]{\setlength{\fboxsep}{6pt}\refstepcounter{myteocounter}\leftbar{black} \hspace*{-\dimexpr\parindent+15pt} \colorbox{black}{\color{white}\bfseries\sffamily Teorema \themyteocounter\ #1}\smallskip\par\noindent}%
{\endleftbar}

\begin{document}    

\chapter{Some Chapter}
\section{Some Section}

\begin{myteo}[I do this]
\lipsum[1]
\end{myteo}

\end{document}

答案1

主要问题是您的myteo环境接受一个强制参数而没有可选参数,但您只尝试传递一个可选参数。因此,的实际强制参数接收myteo接下来的内容,并在后面的输入中进行括号平衡\begin{myteo},这是一个单[字符标记:以 开头的那个[I do this](但请注意[I do this]不是myteo被你的环境视为参数——仅仅[是;这和你写的一样\begin{myteo}{[}I do this] (...))。然后剩余的I do this]标记成为环境主体的一部分,你确实在定理文本的开头找到了它们!

坏的

因此,您本质上需要修复以下参数声明myteo

\newenvironment{myteo}[1][]{...}{...}

(这假设您想要一个可选参数,其默认值为空)。您可以根据此参数是否为空来使用包\ifblank中的不同操作etoolbox,如下所示。我还改进了一些通常对此类环境有利的东西(添加了\ignorespaces、、);我还添加了字符以避免在环境定义中出现多余的\unskip空格。\ignorespacesafterend%leftbar

\documentclass{article}
\usepackage{lipsum}
\usepackage{etoolbox}
\usepackage{xcolor}
\usepackage{framed}

\renewenvironment{leftbar}[2][\hsize]
{%
    \def\FrameCommand
    {%
        {\color{#2}\vrule width 3pt}%
        \hspace{1pt}%
    }%
    \MakeFramed{\hsize#1\advance\hsize-\width\FrameRestore}%
}
{\endMakeFramed}

\newcounter{myteocounter}
\counterwithin{myteocounter}{section}

\newenvironment{myteo}[1][]{%
  \setlength{\fboxsep}{6pt}%
  \refstepcounter{myteocounter}%
  \begingroup
  \leftbar{black}%
  \hspace*{-\dimexpr\parindent+15pt}%
  \colorbox{black}{%
     \color{white}\bfseries\sffamily Teorema \themyteocounter
     \ifblank{#1}{}{ (#1)}%
  }%
  \smallskip\par\noindent
  \ignorespaces
}{%
  \unskip
  \endleftbar
  \endgroup
  \ignorespacesafterend
}

\begin{document}

\section{Some Section}

\begin{myteo}[I do this]
\lipsum[1]
\end{myteo}

\end{document}

修复代码截图

相关内容