Synctex: haga que funcione con el entorno accediendo a su contenido (por ejemplo, la opción environ o xparse +b)

Synctex: haga que funcione con el entorno accediendo a su contenido (por ejemplo, la opción environ o xparse +b)

Si creo un entorno usando environand \BODYo xparseand +b, la funcionalidad synctex se interrumpe: en lugar de ir a la línea apropiada, va al final del entorno. Supongo que el hecho de que \BODYesté puesto en una macro perturba LaTeX, pero tengo curiosidad por saber si puedo solucionarlo de alguna manera (eventualmente en lualatex)

MWE

\documentclass[]{article}
\usepackage{environ}% http://ctan.org/pkg/environ

%% The +b is needed because in real life the text may be moved to another file
\NewDocumentEnvironment{testSynctex}{s+b}{
  \IfBooleanTF{#1}{}{#2}%
}{}

\NewEnviron{testSynctexEnviron}{%
  \BODY
}

\begin{document}

\section{xparse}

\begin{testSynctex}
  This

  is

  a

  long

  text

  try

  to synctex

  me !
\end{testSynctex}

\section{xparse*}

\begin{testSynctex}*
  This

  text
  should

  be

  hidden
\end{testSynctex}

\section{environ}

\begin{testSynctexEnviron}
  This

  is

  a

  long

  text

  try

  to synctex

  me !
\end{testSynctexEnviron}

\end{document}

EDITAR

La solución propuesta por el usuario202729 funciona muy bien para el MWE anterior (y definitivamente responde parte de mi pregunta y seguramente resultará útil si no puedo encontrar una respuesta más generalizable). Sin embargo, aquí hay otro MWE que me gustaría resolver donde la solución propuesta por el usuario202729 ya no funciona:

Estoy duplicando un texto entre dos secciones (escribiendo primero el contenido en un archivo antes de ingresar ese archivo). Desafortunadamente, esto rompe el synctex: no sólo para el texto copiado (va al archivo ficticio en lugar del archivo principal), sino también para el texto inicial (va al final del entorno).

¿Sería posible hacer que synctex funcione al menos para el texto de la primera sección? Y si puedes hacer que funcione también para el texto de la segunda sección… sería fantástico.

MWE:

\documentclass{article}
\def\nameOfFile{mydummyfile.tex}

%% Write to a file
\newwrite\appendwrite
\NewDocumentCommand\writetofile{m+m}{%
  %% Open the file
  \immediate\openout\appendwrite #1\relax%
  %% Write the text to the file
  \immediate\write\appendwrite{#2}%
  %% Close the file
  \immediate\closeout\appendwrite%
}
  
\NewDocumentEnvironment{duplicateContentKeepSynctex}{+b}{%
  #1%
  \writetofile{\nameOfFile}{#1}%
}{}

\begin{document}

\section{Main body}

\begin{duplicateContentKeepSynctex}
  This content is duplicated to another section.

  However synctex does not work in both sections.

  Ideally I'd love to make synctex work in both sections (in such a way that it always links to the main file, NOT mydummyfile).

  But I guess it's impossible.

  But at least, is it possible to make it work for the first section?
\end{duplicateContentKeepSynctex}

\section{Duplicated section}

\input{\nameOfFile}

\end{document}

Respuesta1

No veo cómo eso sería posible en un lenguaje de macroexpansión. El contenido de una macro no se procesa, por lo que solo puede obtener mensajes de error o marcadores de sincronización donde se usa y que pueden no estar ni cerca de la definición. En estos casos, la macro interna que guarda el cuerpo del entorno se usa cerca de la definición, por lo que los datos de sincronización están cerca de la fuente, pero para enviar mensajes de texto, su ejemplo es como

\def\abc{
some text

XXX

that gets saved here
}

multiple pages of arbitrary document source

\abc

y usted está pidiendo que synctex asocie XXX con la línea 4 en medio de la definición, \abcno con una línea "varias páginas más tarde" donde \abcse usa.

Respuesta2

Muy bien, la solución.

Si se compila con lualatex, ambas secciones tendrán synctex conservado; de lo contrario, solo se conservará la primera sección.

%! TEX program = pdflatex

\documentclass{article}
\usepackage{saveenv}
\usepackage{currfile}
\usepackage{rescansync}

  
\ExplSyntaxOn
\NewDocumentEnvironment{duplicateContentKeepSynctex}{}{%
  \rescansyncSaveenvghostPacked \savedcontent
}{
  \endrescansyncSaveenvghostPacked
}
\ExplSyntaxOff

\begin{document}

\section{Main body}

\begin{duplicateContentKeepSynctex}
  This content is duplicated to another section.

  However synctex does not work in both sections.

  Ideally I'd love to make synctex work in both sections (in such a way that it always links to the main file, NOT mydummyfile).

  But I guess it's impossible.

  But at least, is it possible to make it work for the first section?
\end{duplicateContentKeepSynctex}

\section{Duplicated section}

\rescansyncPacked \savedcontent

\end{document}

En realidad, no escribe el contenido en un archivo, el contenido se almacena en \savedcontentalgún formato peculiar que se supone que el usuario no debe tocar. Si el usuario desea manipular el contenido manualmente, utilice la API programática del rescansyncpaquete.

Nota

información relacionada