僅當它適合一行時居中引用

僅當它適合一行時居中引用

我為報價環境編寫了一些程式碼。我希望報價僅在足夠短以適合一行時才居中,否則不應居中。這是程式碼

\documentclass{article}
\usepackage{changepage, xparse}
\ExplSyntaxOn

\NewDocumentEnvironment{ myquote }{ o }{
  \begin{center}
  \begin{adjustwidth}{50pt}{50pt}
  \begin{itshape}
}{
  \end{itshape}
  \end{adjustwidth}
  \end{center}  
  \IfValueT{ #1 }{
    \vspace{-0.15cm}
    \begin{adjustwidth}{0pt}{20pt}
    \flushright { \small -\hspace{2pt}#1\hspace{2pt}- }
    \end{adjustwidth}
    \vspace{0.3cm}
  }
}

\ExplSyntaxOff

\begin{document}
\begin{myquote}[Someone]
This should be centered.
\end{myquote}

\begin{myquote}[Someone else]
This is a longer quote and therefore shouldn't be centered. This is some more text.
\end{myquote}
\end{document}

在此輸入影像描述

我怎麼能這樣做呢?

答案1

這使用, 並檢查內部\NewEnviron斜體的寬度。如果小於,則在前面新增一個。\BODY\hbox\linewidth\hfil\BODY

\documentclass{article}
\usepackage{changepage, environ}
\usepackage[pass,showframe]{geometry}

\NewEnviron{myquote}[1][\relax]{
  \begin{center}
  \begin{adjustwidth}{50pt}{50pt}
  \setbox0=\hbox{\itshape\BODY}%
  \begin{itshape}
  \ifdim\wd0>\linewidth\relax\BODY\else\hfil\BODY\fi
  \end{itshape}
  \end{adjustwidth}
  \end{center}  
  \ifx\relax#1\relax\else
    \vspace{-0.15cm}
    \begin{adjustwidth}{0pt}{20pt}
    \flushright { \small -\hspace{2pt}#1\hspace{2pt}- }
    \end{adjustwidth}
    \vspace{0.3cm}
  \fi
}


\begin{document}
\begin{myquote}[Someone]
This should be centered.
\end{myquote}

\begin{myquote}[Someone else]
This is a bit longer, but should still be centered.
\end{myquote}

\begin{myquote}[Someone else]
This is a longer quote and therefore shouldn't be centered. This is some more text.
\end{myquote}

\end{document}

在此輸入影像描述

相關內容