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

Conditional statements are not working when I use preprocessor extensions #64

Open JmyL opened 8 years ago

JmyL commented 8 years ago

Conditional statements are not working when I use 'mathematical-treeprocessor' extension. The "hello world" string doesn't apear when using 'preprossor extension'.

:enable-string:

ifdef::enable-string[]
hello world!
endif::[]

Conditional statements are working well when I delete mathematical-preprocessor code on 'mathematical-treeprocessor.rb'.

Extensions.register do
  # if @document.basebackend? 'html'
  //inline_macro MathematicalInlineMacro
  treeprocessor MathematicalTreeprocessor
end

I've tested several other preprocessors, it's same on other preprocessors make same problem too.

Conditional statements which looks for CLI attributes works well. Only conditional satements which looks for DOCUMENT attributes are not working.

mojavelinux commented 8 years ago

Unfortunately, this is one of the limitations of a preprocessor. A preprocessor does not see the structure of the AsciiDoc document in any way, aside from the preprocessor directives. As far as the preprocessor is concerned, it's just handling lines of text, some of which may contain preprocessor directives.

If you want the preprocessor to know about the attributes defined in the document header, you first need to parse the document up to the end of the document header, push those attributes into the document object, then allow the preprocessor to proceed.

I've done something similar in the AsciiDoc coalescer script. See https://github.com/asciidoctor/asciidoctor-extensions-lab/blob/master/scripts/asciidoc-coalescer.rb#L46-L53

What we may want to consider is adding an option to the Preprocessor that tells it to parse the document header in order to extract the attributes, then run on the remaining lines of code. That change would need to happen in core.

stephenramm commented 7 years ago

There is a fix. Instead of returning a new Reader from your preprocessor, return a new PreprocessorReader initialised with your processed raw lines, thus:

class myPreprocessor <Asciidoctor::Extensions::Preprocessor
  def process document, reader
    Asciidoctor::PreprocessorReader.new document, reader.lines.map {|line|
      # do your stuff here..
      line
     }
  end
end