Espaço vertical flexível simultâneo com quebras de página

Espaço vertical flexível simultâneo com quebras de página

Encontrando um problema que não consigo entender. Em essência, tenho uma página que contém algum texto, possivelmente algumas equações, alguns gráficos e talvez uma tabela, todos separados por espaços em branco flexíveis. Às vezes, tudo cabe em uma página, mas às vezes os gráficos são muito grandes, sendo necessárias várias páginas.

Digamos que eu tenha 3 gráficos. No caso de serem todos grandes demais para caber em uma página, esperaria que os dois primeiros gráficos permanecessem na primeira página, distribuídos uniformemente junto com qualquer texto anterior, e o terceiro gráfico ficaria na próxima página junto com o seguinte texto ou tabelas, etc. No entanto, meu código sempre mantém todos os três gráficos juntos.

Tenho a impressão de que é devido à \vspacecriação de um unbreakable vbox, mas não sei de que outra forma lidar com o que quero sem adicionar manualmente um \clearpageou similar. Isto é indesejável; o objetivo final são modelos que façam isso automaticamente para mim, é claro!

Aqui está um MWE. Neste exemplo, as imagens A e B terminam na página 2. Meu desejo é que a imagem A termine na página 1, e B, C e a próxima seção na página 2.

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}
\usepackage[T1]{fontenc}
\usepackage[margin=0.8in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mwe}

\begin{document}

\mainmatter

\section{A section}

\subsection{the first subsection}

Some text here

\vfill

\begin{center}
\textbf{Some title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-a}

\vfill

\textbf{More title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-b}

\vfill

\textbf{Even more title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-c}
\end{center}

\subsection{The next subsection}

\end{document}

Resultado: Resultado

Representação aproximada do MSPaint do que eu espero: insira a descrição da imagem aqui

Responder1

O problema

O que está acontecendo no seu MWE é que a interação entre pulos infinitamente extensíveis e a penalidade negativa (quebra de página) introduzida por centerestá fazendo com que o algoritmo de quebra de página do TeX conclua que não há lugar melhor para uma quebra de página do que logo antes do conteúdo do centerambiente . É por isso que usar \centeringem vez do centermeio ambiente ajuda. No entanto, problemas semelhantes ainda surgirão em torno dos títulos das seções e dos ambientes de lista.

Uma penalidade negativa (por quebra de página) é inserida no início do centerambiente porque ele utiliza internamente um trivliste o início de uma lista é considerado um bom local para uma quebra de página. Essa penalidade negativa incentiva o TeX a quebrar a página neste ponto se já for um lugar adequado para fazê-lo, com o que quero dizer que fazer isso não faria com que a cola fosse esticada demais. Como você inseriu uma cola infinitamente extensível, no entanto, nenhum estiramento é demais, o que leva à conclusão de que centeré preferível finalizar a página no início do ambiente do que fazê-lo quando a página estiver cheia. Não há custo associado à quebra de página devido ao estiramento infinito, mas tem a vantagem (na mente do TeX) de que a quebra ocorre em um local natural para ela.

Uma descrição detalhada do algoritmo de quebra de página pode ser encontrada na seção 27.4 doTeX por tópico.

Além das quebras de página forçadas, eupensarpenalidades negativas que são (por padrão) inseridas apenas nos seguintes locais:

  • acima dos títulos das seções,
  • em torno de ambientes de lista (que incluem center, por exemplo, ambientes de teorema, uma vez que estes são implementados usando \trivlist),
  • entre \items,
  • por vários comandos de usuário que fazem isso explicitamente ( \pagebreak[n], \smallbreak, etc.),
  • outro? (Alguém por favor me avise se eu perdi alguma coisa)

Uma solução/solução alternativa

Para evitar que quebras de página ocorram antes do necessário devido a penalidades negativas, você pode definir essas penalidades negativas como zero. Para fazer isso para títulos de seção e listas dentro/em torno, adicione as seguintes linhas ao seu preâmbulo:

\makeatletter       %% <- make @ usable in command sequences
\@secpenalty=0      %% <- don't encourage breaks before section heading
\@beginparpenalty=0 %% <- don't encourage breaks at start of list environments
\@endparpenalty=0   %% <- don't encourage breaks at end of list environments
\@itempenalty=0     %% <- don't encourage breaks between items
\makeatother        %% <- revert @

Um efeito colateral de fazer isso é, obviamente, que as quebras de página não serão mais incentivadas nesses locais. (Eles ainda ficarão desanimados, por exemplodepoiscabeçalhos de seção, no entanto.) Isso também não irá ajudá-lo se penalidades negativas forem inseridas por qualquer outro tipo de ambiente/comando, então tenha cuidado com isso.

Eu defini uma versão do figureambiente que acho que faz mais ou menos o que você deseja (desde que todas as penalidades acima sejam definidas como zero). Infinitamente extensível que não pode passar para a página anterior/seguinte será inserido ao redor dele. Você poderia definir de forma semelhante um shamtamtableambiente para tabelas.

\newcommand*\topvfill{%
  \par                      %% <- switch to vertical mode
  \penalty 0                %% <- allow a page break here, but don't encourage it
  \vspace*{0pt plus 1fill}% %% <- unremovable infinitely stretchable space
}
\newcommand*\bottomvfill{%
  \par                      %% <- switch to vertical mode
  \vspace{0pt plus 1fill}%  %% <- infinitely stretchable space
  \penalty 0                %% <- allow a page break here
}

\usepackage{float} % <- for the [H] option
\newenvironment{shamtamfig}{%
  \topvfill    %% <- insert flexible space above
  \figure[H]%  %% <- begin inner figure environment
  \centering   %% <- horizontally centre content
}{%
  \endfigure   %% <- end figure environment
  \bottomvfill %% <- insert flexible space below
}

Seu MWE com essas mudanças

Aqui está o seu MWE \vfillsubstituído por \beakablevfille com as penalidades negativas acima mencionadas definidas como zero. Adicionei a showframeopção de geometrymostrar a borda da área de texto e fiz algumas pequenas alterações para tornar esta demonstração mais clara.

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}
\usepackage[margin=0.8in, showframe]{geometry} %% <- added showframe for demonstration
\usepackage{graphicx}

\makeatletter %% <- make @ usable in command sequences
\@beginparpenalty=0 % <- start of list env
\@endparpenalty=0   % <- end of list env
\@itempenalty=0     % <- between items
\@secpenalty=0      % <- before section heading
\makeatother  %% <- revert @

\newcommand*\topvfill{%
  \par                      %% <- switch to vertical mode
  \penalty 0                %% <- allow a page break here, but don't encourage it
  \vspace*{0pt plus 1fill}% %% <- unremovable infinitely stretchable space
}
\newcommand*\bottomvfill{%
  \par                      %% <- switch to vertical mode
  \vspace{0pt plus 1fill}%  %% <- infinitely stretchable space
  \penalty 0                %% <- allow a page break here
}
\def\midvfill{%
  \par                       %% <- switch to vertical mode
  \vspace{0pt plus 1fill}%   %% <- infinitely stretchable space
  \penalty 0                 %% <- allow a page break here, but don't encourage it
  \vspace{0pt plus -1fill}%  %% <- cancels out the previous \vspace if no page break occurred
  \vspace*{0pt plus 1fill}%  %% <- unbreakable/unremovable infinitely stretchable space
}

\usepackage{float} % <- for the [H] option

\newenvironment{shamtamfig}{%
  \topvfill    %% <- insert flexible space above
  \figure[H]%  %% <- begin inner figure environment
  \centering   %% <- horizontally centre content
}{%
  \endfigure   %% <- end figure environment
  \bottomvfill %% <- insert flexible space below
}

\usepackage{blindtext} % <- for demonstration purposes

\begin{document}

\section{A section}

\subsection{the first subsection}

\blindtext[2]

\blindtext

\begin{shamtamfig}
    \textbf{Some title text}\par
    \includegraphics[width=0.6\textwidth]{example-image-a}
\end{shamtamfig}

\begin{shamtamfig}
    \textbf{More title text}\par
    \includegraphics[width=0.4\textwidth]{example-image-b}
\end{shamtamfig}

\begin{shamtamfig}
    \textbf{Even more title text}\par
    \includegraphics[width=0.4\textwidth]{example-image-c}
\end{shamtamfig}

\subsection{The next subsection}

\blindtext

\blinditemize

\blindtext[2]

\begin{shamtamfig}
    \textbf{Even more title text}\par
    \includegraphics[width=0.6\textwidth]{example-image}
\end{shamtamfig}

\end{document}

Por diversão, você pode tentar comentar algumas linhas \@...penalty=0neste exemplo para ver o efeito que essas linhas têm.

primeira página segunda página terceira página

Responder2

insira a descrição da imagem aqui

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}

\usepackage[T1]{fontenc}
\usepackage[margin=0.8in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mwe}

\begin{document}

%\pagestyle{fancy}

\mainmatter

\section{A section}

\subsection{the first subsection}

Some text here

\vfill

{\centering
\textbf{Some title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-a}


\vfill

\textbf{More title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-b}

\vfill

\textbf{Even more title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-c}

}

\subsection{The next subsection}

\end{document}

Você tem um pouco mais de sorte, \centeringmas na verdade o problema é usar, \\*em vez de seccionamento ou \itemcomandos adequados. No escopo de \centering(e center) \\é realmente \parmais do que sua definição usual de \newlineque significa que ele exerce o quebra de página, \\*adiciona uma \nobreakpenalidade, então se acontecer de uma quebra de página ser considerada após o título, uma quebra é evitada por causa do *mas um a quebra de penalidade zero está disponível antes da primeira imagem devido à \vfilldisponibilidade para preencher o espaço, então o TeX faz essa quebra de página em vez de olhar para frente.


Uma marcação talvez melhor, evitando o uso de alterações de fonte com espaçamento explícito e \\em favor da \captionmarcação látex mais idiomática, seria

insira a descrição da imagem aqui

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}

\usepackage[T1]{fontenc}
\usepackage[margin=0.8in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mwe,float}

\begin{document}

%\pagestyle{fancy}

\mainmatter

\section{A section}

\subsection{the first subsection}

Some text here

\begin{figure}[H]
  \centering
\caption{Some title text}
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-a}  
\end{figure}

\begin{figure}[H]
  \centering
\caption{Some title text}
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-b}  
\end{figure}

\begin{figure}[H]
  \centering
\caption{Some title text}
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-c}  
\end{figure}



\subsection{The next subsection}

\end{document}

Você pode usar os recursos do float (e relacionados caption) para personalizar a formatação da legenda conforme necessário.

Responder3

Não tenho certeza do que você quer dizer com "espaço em branco flexível", mas você pode definir um novo comando que seria usado \vspacecom um "comprimento flexível" predefinido.

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}
\usepackage[T1]{fontenc}
\usepackage[margin=0.8in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mwe}

\newlength{\mylength}
\setlength{\mylength}{20pt plus 10pt minus 5pt}
\newcommand{\myskip}{\vspace{\mylength}}
\begin{document}

\mainmatter

\section{A section}

\subsection{the first subsection}

Some text here

\myskip

\begin{center}
\textbf{Some title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-a}

\myskip

\textbf{More title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-b}

\myskip

\textbf{Even more title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-c}
\end{center}

\subsection{The next subsection}

\end{document}

PS: Não tenho certeza se entendi a pergunta, então fique à vontade para me pedir para excluí-la.

Responder4

Se quiser usar centeré melhor colocar cada bloco em seu próprio ambiente.

\documentclass[letterpaper,10pt,article,oneside,openany]{memoir}
\usepackage[T1]{fontenc}
\usepackage[margin=0.8in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{mwe}

\begin{document}    
\mainmatter    
\section{A section}    
\subsection{the first subsection}    
Some text here    
\vfill    
\begin{center}
\textbf{Some title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-a}
\end{center}    
\vfill    
\begin{center}
\textbf{More title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-b}
\end{center}    
\vfill    
\begin{center}
\textbf{Even more title text} \\*
\includegraphics[width=0.75\textwidth,keepaspectratio]{example-image-c}
\end{center}    
\subsection{The next subsection}    

\end{document}

informação relacionada