Centralize a citação apenas se couber em uma linha

Centralize a citação apenas se couber em uma linha

Escrevi algum código para um ambiente de cotação. Gostaria que a citação fosse centralizada apenas se for curta o suficiente para caber em uma linha, caso contrário, não deveria ser centralizada. Este é o código

\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}

insira a descrição da imagem aqui

Como eu poderia fazer isso?

Responder1

Isso usa \NewEnvirone verifica a largura do itálico \BODYdentro de um arquivo \hbox. Se for menor que \linewidth, an \hfilserá anexado a \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}

insira a descrição da imagem aqui

informação relacionada