Re: Create extension to embed source code

Posted by abelsromero on
URL: https://discuss.asciidoctor.org/Create-extension-to-embed-source-code-tp3645p3654.html

Hi,

I’ve been doing some tests and I think I can shed some light on this case. Not the final solution though, but we can work together on it.

First of all, there is no special reason to use inline extension or block extension. Maybe, for simplicity, since you want to insert a block, it’s better to use another block as a reference.
Aswering you last question, note that this two lines are not the same:
  my-custom-extension::doSomething[withOptions] --> Note the double colons. This is a block is using a short notation to define a block. See http://asciidoctor.org/docs/user-manual/#role (Shorthand Asciidoctor block syntax)
  my-custom-extension:doSomething[withOptions] --> This is an inline macro


Now, back to the extension, I don’t think any of those extensions will work. As described in the manual http://asciidoctor.org/docs/user-manual/#include-directive
Include directives are handled by the preprocessor, so they are oblivious to the structure of the document. They are primarily just a file merger, with one exception. The include directives can resolve document-level attributes.
Even if you could insert the “include” directive, it won’t work because the content will not be fetched. As I understand includes must be dealt within a Preprocessor or IncludePreprocessor extension.
Both extensions allow to parse the text through a PreprocessorReader, which contains the method ‘push_include’.
void push_include(String data, String file, String path, int lineNumber, Map<String, Object> attributes);
‘data’ is basically a string containing the text to include and ‘lineNumber’ is the original line to replace.
You could iterate over the document reading line by line (and counting the line), check if it begins by ‘my-custom-extension’, then retrieve the content, and finally add the source block header/footer.

Here is a example of Preprocessor that shows how to manualy include some content: https://github.com/asciidoctor/asciidoctorj/blob/asciidoctorj-1.6.0/asciidoctorj-core/src/test/java/org/asciidoctor/extension/WhenJavaExtensionIsRegistered.java#L127-L185