asciidoctor / asciidoctor-extensions-lab

A lab for testing and demonstrating Asciidoctor extensions. Please do not use this code in production. If you want to use one of these extensions in your application, create a new project, import the code, and distribute it as a RubyGem. You can then request to make it a top-level project under the Asciidoctor organization.
Other
104 stars 101 forks source link

Using the Preprocessor ignores ifdef directives #123

Open ungive opened 3 years ago

ungive commented 3 years ago

Extensions::Preprocessor breaks ifdef directives. This was reported previously in #62.

I made these changes: https://github.com/vonas/asciidoctor-extensions-lab/commit/b0a42dc7c09fe9412f2bc711a4d5dbb151df5ac7

I ran the following command with corresponding input and part of the output:

asciidoctor -r ./lib/tex-preprocessor.rb lib/tex-preprocessor/sample.adoc
:first:

ifndef::first[]
Hidden
endif::first[]

:first!:

ifndef::first[]
Visible
endif::first[]
<div class="paragraph">
<p>Hidden</p>
</div>
<div class="paragraph">
<p>Visible</p>
</div>

The gist of the extension code is this:

Extensions.register do
  preprocessor TeXPreprocessor
end

class TeXPreprocessor < Extensions::Preprocessor
  def process document, reader
    return reader if reader.eof?
    reader.unshift_lines reader.read_lines  # this is the culprit
    reader
  end
end

Adding reader.unshift_lines reader.read_lines breaks the conditional ifdef directives.

mojavelinux commented 3 years ago

This is a known limitation of a preprocessor and why I strongly discourage using it to manipulate any lines. Instead it should be treated only as an event. Manipulating lines can be done, but it must be done extremely carefully to avoid exactly these types of side effects. So it's a "caveat emptor" kind of extension point.