[Tex/LaTex] Centering left justified text

horizontal alignmentminipage

I need to define a new environment that contains a minipage centered on the current page and with text left-justified.

Something like:

\newenvironment{texto}{
   \begin{center} % so the minipage is centered
   \begin{minipage}[t][\textwidth]
   \begin{flushleft} % so the minipage's text is left justified
}{
   \end{flushleft}
   \end{minipage}
   \end{center}
}

I've been trying for hours without luck so far.

If it was possible to put the minipage inside a centered makebox inside the new environment it would be possible, but there's no makebox environment.

EDIT:

\documentclass[a4paper,10pt,twoside,onecolumn,openright,final]{book}
\newenvironment{code-block}{
    \begin{center}
    \begin{minipage}[t]{\textwidth}
    \raggedright
}{
    \end{minipage}
    \end{center}
}

\begin{document}

a completely random line, filled with random words, or perhaps not!

\begin{code-block}
pineapples with mustard
\end{code-block}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

\end{document}

result:

enter image description here

Best Answer

To allow for a variable-width minipage environment, you need the varwidth package. From the package documentation:

The package deļ¬nes a varwidth environment (based on minipage) which is an analogue of minipage, but whose resulting width is the natural width of its contents.

The minimal example as presented in the package documentation gives a view on what means:

An example of the varwidth environment from the package documentation

So, alter Stefan's answer in the following way:

\usepackage{varwidth}% http://ctan.org/pkg/varwidth
\newenvironment{texto}{%
  \begin{center} % so the minipage is centered
  \begin{varwidth}[t]{\textwidth}
  \raggedright % so the minipage's text is left justified
}{%
  \end{varwidth}
  \end{center}
}

varwidth vs minipage

Related Question