
ParaComandos/ambiente de compilação parcial?, gostaria de adicionar \begin{comment}
ou \comment
no início do documento (para poder desativá-lo em outro lugar do código).
Então, mesmo que no âmbito mais amplo das coisas seja inútil - neste MWE, como exercício, eu gostaria que todo o texto fosse deixado em branco, basicamente, condicionalmente através da linha de comando (o resultado seria uma página em branco, ou mesmo sem pdf).
EDITAR: No entanto, eu gostaria que isso fosse feito de tal maneira, para que eu pudesse adicionar \end{comment}
/ \begin{comment}
posteriormente arbitrariamente o documento e terapenasesse trecho é compilado.
\documentclass[11pt]{book}
\usepackage{lipsum}
\ifx\doskip\relax
\typeout{DOSKIP}
\usepackage{etoolbox}
\usepackage{comment}
% https://tex.stackexchange.com/questions/14135/how-to-automatically-add-text-immediately-after-begindocument
%\AtBeginDocument{\comment} % ! Extra \endgroup.
%\AtBeginDocument{\begin{comment}} % Runaway argument? ! File ended while scanning use of \next.
%\AfterEndPreamble{\comment} % ! Extra \endgroup.
%\AfterEndPreamble{\begin{comment}} % Runaway argument? ! File ended while scanning use of \next.
%\AtEndDocument{\endcomment}%{\end{comment}}
% desperate try (also fails w/ ! Extra \endgroup.):
\protected\def\startcomment{\expandafter\comment}
\AtEndPreamble{
\startcomment
} % ! Extra \endgroup.
\fi
\begin{document}
\chapter{Some chapter}
\section{Section One}
\lipsum[1-3]
% later I might want to use here:
% \end{comment}
% \lipsum[5] % this would be typeset
% \begin{comment} % from this point on, again blanked
\end{document}
A idéia é que o documento fique "em branco" se o Latex for chamado na linha de comando via
pdflatex "\let\doskip\relax\input{test.tex}"
... porém, claramente existem alguns erros de agrupamento; caso contrário, sem a intervenção, apenas usando pdflatex test.tex
, funciona bem.
Alguma idéia de como isso poderia ser implementado?
EDIT2: mais perto, mas ainda não chegou: já vi em kpsewhich comment.sty
"Outros ambientes de 'comentário' são definidos por ... \excludecoment{versionb} ; Esses ambientes são usados como \begin{versiona} ... \end{versiona} com os comandos de abertura e fechamento novamente em uma linha própria. Este não é um ambiente LaTeX: para um comentário incluído, as linhas \begin e \end agem como se não existissem. Em particular, eles não implicam agrupamento ..."
Portanto, no exemplo abaixo, que usa \excludecomment{versionb}
, o início {document} é substituído com sucesso, a primeira parte é ignorada, o comentário é interrompido, \lipsum[5]
é digitado e o documento é compilado sem erros - mas, além disso, é muito difícil fechar corretamente qualquer um deles ininterrupto (documento totalmente em branco) ou continue com o apagamento depois de ter sido interrompido:
\documentclass[11pt]{book}
\usepackage{lipsum}
\usepackage{trace}
\ifx\doskip\relax
\typeout{DOSKIP}
\usepackage{etoolbox}
\usepackage{comment}
\excludecomment{versionb}
%\AtEndPreamble{ % here causes ! LaTeX Error: Missing \begin{document}.
\AtBeginDocument{%
% \expandafter\begin{versionb}\relax
\begin{versionb}
} %
%\AtEndDocument{\end{versionb}} % ! LaTeX Error: \begin{document} ended by \end{versionb}.
\fi
% \traceon
\begin{document}
\chapter{Some chapter}
\section{Section One}
\lipsum[1-3]
\end{versionb}
\lipsum[5]
% \begin{versionb}
%% \end{versionb} % can this be implicit, as per \AtEndDocument?
\end{document}
%%ENNDDD
Um \typeout
pode ser adicionado a esta macro em comment.sty
:
\gdef\ProcessCommentLine#1^^M{\def\test{#1}
\typeout{test: \meaning\test, \meaning\expandafter \csname End\CurrentComment Test\endcsname}
... então, se não houver um \end{versionb}
antes do \lipsum[5]
, podemos ver que o problema ocorre porque as linhas são tentadas para serem lidas além do final do arquivo:
...
test: macro:->\end{document}, \expandafter\end{versionb}
test: macro:->%%ENNDDD, \expandafter\end{versionb}
test: macro:->, \expandafter\end{versionb}
)
Runaway argument?
! File ended while scanning use of \next.
<inserted text>
\par
<*> \let\doskip\relax\input{test.tex}
Então, ainda preciso de ajuda sobre como fazer esse código funcionar em todas as circunstâncias...
Responder1
Você pode usar o código a seguir em algum lugar do preâmbulo depois de \documentclass
.
\def\doskipA{\begin{document}\end{document}}
\ifx\doskip\relax \expandafter\doskipA\fi
Responder2
Ok, finalmente cheguei a algum lugar, embora talvez não seja o ideal. O MWE abaixo se comporta assim:
Se compilado com
pdflatex test.tex
, ocomment
material será ignorado e o documento será totalmente compilado; mas haverá esses dois avisos gerados no log (não sei como consertar isso):(\end occurred inside a group at level 2) ### semi simple group (level 2) entered at line 86 (\begingroup) ### semi simple group (level 1) entered at line 86 (\begingroup) ### bottom level...
Se compilado com
pdflatex "\let\doskip\relax\input{test.tex}"
; então há um\excludecomment
definido, chamadoSKIPLINES
e\begin{document}
inicia-o automaticamente; o código é compilado sem avisos, e apenas o segmento entre\end{SKIPLINES}
e\begin{SKIPLINES}
(observe a ordem) que aqui está\lipsum[5]
será digitado. Também mensagens como estas serão enviadas para o terminal:... test: macro:->, macro:->\end{SKIPLINES} noend macro:-> macro:->\end{document} test: macro:->\end{document}, macro:->\end{SKIPLINES} yesend
Eu acho que isso exige \excludecomment
que agrupamentos adicionais (?) sejam evitados. No entanto, ainda existem alguns hacks necessários e, portanto, o código inclui versões modificadas de {comment}
's \excludecomment
e \ProcessCommentLine
. Em particular, como observou @UlrikeFischer, se acontecer de o Latex estar no "modo de comentário" durante a leitura \end{document}
, ele será ignorado, resultando em erros; portanto, o redefinido \ProcessCommentLine
verifica adicionalmente \end{document}
como um token para interromper o modo de comentário e, em seguida, executa novamente o adequado \end{document}
se essa condição for encontrada.
Isso significa que deve-se ser capaz de, no \doskip
modo, adicionar \end{SKIPLINES}
e \begin{SKIPLINES}
à vontade, definir partes das regiões compiláveis, sem precisar se preocupar se elas estão fechadas adequadamente para \end{document}
: um único par de \end{SKIPLINES}
e \begin{SKIPLINES}
deve funcionar, tão bem quanto um documento sem nenhum deles (ou com um adicional \end{SKIPLINES}
).
Obviamente, esta não é uma solução verdadeiramente adequada (esta não funciona com \input
arquivos ted), então espero que eventualmente surja uma resposta mais erudita; mas por enquanto, aqui está o MWE (e desculpe pela bagunça):
\documentclass[11pt]{book}
\usepackage{lipsum}
\usepackage{trace}
\newif\ifSKIPLINESAct % if active
\ifx\doskip\relax
\typeout{DOSKIP}
\usepackage{etoolbox}
\usepackage{comment}
\usepackage{xstring}
\def\excludecommentB
#1{\message{Excluding comment '#1'}%
%\csarg\newif{if#1Act}% declare globally; http://tex.stackexchange.com/questions/228994/handling-a-conditionally-defined-newif-nested-in-an-ifx-conditional
\csarg\def{#1}{\endgroup \message{Excluding '#1' comment.}%
\csname #1Acttrue\endcsname
\begingroup
\DefaultCutFileName \def\ProcessCutFile{}%
\def\ThisComment####1{}\ProcessComment{#1}}%
\csarg\def{After#1Comment}{%
\global\csname #1Actfalse\endcsname% must globalize - inside a group here!
\CloseAndInputCutFile \endgroup}
\CommentEndDef{#1}}
% redef this too:
\csarg\xdef{EndDocTest}{\string\end\string{document\string}}
% \showme\EndDocTest
{\catcode`\^^M=12 \endlinechar=-1 %
\gdef\xComment#1^^M{\ProcessCommentLine}
\gdef\ProcessCommentLine#1^^M{\def\test{#1}
\typeout{test: \meaning\test, \expandafter\meaning \csname End\CurrentComment Test\endcsname}
\csarg\ifx{End\CurrentComment Test}\test
\edef\next{\endgroup\noexpand\EndOfComment{\CurrentComment}}%
\else \ThisComment{#1}\let\next\ProcessCommentLine
\fi%
% also add for end document; use \IfStrEq else catcodes could be a problem
\IfStrEq*{\EndDocTest}{\test}{%
%\traceon%
\typeout{yesend}%
\def\next{%\endgroup\noexpand\EndOfComment{\CurrentComment}%
\endgroup\noexpand\EndOfComment{\noexpand\CurrentComment}% % must add \noexpand to \CurrentComment, else it leaks and gets typeset in the doc!
%\SKIPLINESActfalse% no; use:
\AfterSKIPLINESComment% % both sets false and ends group
\enddocument%
}%
}{\typeout{noend \meaning\test\space\meaning\EndDocTest}%\ThisComment{#1}\let\next\ProcessCommentLine% don't execute here, just typeout
}%
\next}
}
\excludecommentB{SKIPLINES} % define, also \ifSKIPLINESAct
%\AtEndPreamble{ % here causes ! LaTeX Error: Missing \begin{document}.
\AtBeginDocument{%
% \expandafter\begin{SKIPLINES}\relax
\begin{SKIPLINES}
} % ! Extra \endgroup.
%\AtEndDocument{\end{SKIPLINES}} % ! LaTeX Error: \begin{document} ended by \end{SKIPLINES}. % redefine instead?
%% no need for this:
% \global\let\oldenddocument\enddocument
% \gdef\enddocument{% redefine
% %\ifSKIPLINESAct\expandafter\end\expandafter{SKIPLINES}\fi
% \oldenddocument%
% }
\else
% still need this, when calling without \doskip:
\makeatletter
\newenvironment{SKIPLINES}{%
\begingroup\def\@currenvir{document}%
}{%
% comment.sty: % sabotage LaTeX's environment testing \begingroup\def\@currenvir{#1}\end{#1}
\begingroup\def\@currenvir{SKIPLINES}%\endgroup
}
% \def\endSKIPLINES{\begingroup\def\@currenvir{SKIPLINES}} % nope
\makeatother
\fi
% \traceon
\begin{document}
\chapter{Some chapter}
\section{Section One}
\lipsum[1-3]
% \traceon
\end{SKIPLINES}
% \traceoff
\lipsum[5]
\begin{SKIPLINES} % will cause ### semi simple group (level 2) entered at line 90 if without \doskip and unclosed, but doc will compile
\lipsum[10]
% \end{SKIPLINES} % if this is uncommented when \doskip, it will allow the next typeout to execute (else they will be gobbled)
% these print to stdout only if \end{SKIPLINES} occured last previously:
\typeout{\meaning\endSKIPLINES}
\ifx\doskip\relax
\ifSKIPLINESAct\typeout{SKIPLINES Active}\else\typeout{no SKIPLINES}\fi%
\else
\fi
\end{document}
%%ENNDDD