### Ruby Hello World Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc A basic Ruby program that prints 'Hello world' to the console. This example demonstrates inline code highlighting for Ruby. ```ruby =begin This program will print "Hello world". =end puts 'Hello world' ``` -------------------------------- ### Scala Hello World Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc A simple Scala object that prints 'Hello, world!'. This example showcases inline code highlighting for Scala. ```scala /** * This is a simple scala example */ object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } ``` -------------------------------- ### HTML Document Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc A minimal HTML document structure including a title and a heading. This example demonstrates inline code highlighting for HTML. ```html A Small Hello

Hi

This is very minimal "hello world" HTML document.
``` -------------------------------- ### Java Hello World Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc A standard Java 'Hello World' program. It includes Javadoc comments and demonstrates inline code highlighting for Java. ```java /** * This is a Java "Hello world" example. * @param args arguments * * @since 1.3 */ public class Test { public static void main(String[] args) { System.out.println("Hello World!"); } } ``` -------------------------------- ### Install AsciidoctorJ (Chocolatey) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/README.adoc Shows how to install AsciidoctorJ on Windows using Chocolatey. ```batch C:\> choco install asciidoctorj ``` ```batch C:\> where asciidoctorj ``` ```batch C:\> asciidoctorj -b pdf README.adoc ``` -------------------------------- ### CLI Usage with Bash Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt This Bash snippet provides command-line examples for using AsciidoctorJ to convert documents to HTML and PDF. It requires the asciidoctorj command to be installed and takes AsciiDoc files as input, outputting formatted documents. Limitations include dependency on available backends like PDF conversion tools. ```bash # Basic HTML conversion asciidoctorj document.adoc # Convert to PDF asciidoctorj -b pdf -o output.pdf document.adoc ``` -------------------------------- ### Groovy Code Inclusion Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc An example demonstrating how to include external Groovy code using the 'include' directive. This is useful for organizing larger code blocks. ```groovy include::code_examples/groovy.groovy[] ``` -------------------------------- ### JavaScript Hello World Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc A JavaScript snippet that logs 'Hello World!!' to the console or shows an alert if console is not available. Demonstrates inline code highlighting for JavaScript. ```javascript if (console.log) { // greeting silently console.log('Hello World!!') } else { // greeting in a pop up window alert('Hello World!') } ``` -------------------------------- ### CoffeeScript Code Inclusion Example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-distribution/src/test/resources/code-sample.adoc An example showing how to include external CoffeeScript code using the 'include' directive. Useful for managing CoffeeScript source files. ```coffeescript include::code_examples/coffeeScript.coffee[] ``` -------------------------------- ### Convert AsciiDoc using builder pattern configuration Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/conversion-examples.adoc Illustrates configuration using builder patterns with AttributesBuilder and OptionsBuilder. Creates Asciidoctor instance, builds attributes using AttributesBuilder without calling build(), creates options using OptionsBuilder with attributes reference, then converts sample.adoc. This approach avoids calling build(), get() or asMap() methods on builders. ```java Asciidoctor asciidoctor = Asciidoctor.Factory.create(); // <.> AttributesBuilder attributes = Attributes.builder() .backend("docbook") .icons("font"); // <.> OptionsBuilder options = Options.builder() .inPlace(true) .attributes(attributes); // <.> String outfile = asciidoctor.convertFile(new File("sample.adoc"), options); // <.> ---- <.> Create `Asciidoctor` instance. <.> Defines the attributes as an `AttributesBuilder` by not using `build()`, `get()` or `asMap()`. <.> Defines the options as an `OptionsBuilder` by not using `build()`, `get()` or `asMap()`. <.> Converts the document passing `OptionsBuilder` instance. ``` -------------------------------- ### Source Code Listing Example (Ruby) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/asciidoctorj-documentation/src/test/resources/ast-demo-result.txt Demonstrates how to include a source code listing within an Asciidoctor document. This example uses Ruby for the code snippet. ```ruby puts 'Hello, World!' ``` -------------------------------- ### Ruby 'Hello, World!' Example in Asciidoctor Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/extensions/examples/ast-demo-result.txt A basic 'Hello, World!' program written in Ruby, often embedded within Asciidoctor documents as a source block. This snippet demonstrates a simple output statement. ```ruby puts 'Hello, World!' ``` -------------------------------- ### Update AsciidoctorJ Preprocessor for 2.5.x Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/update-preprocessor-api.adoc Example of a Preprocessor implementation for AsciidoctorJ versions up to 2.5.x. This version's `process` method does not return a Reader object. ```java public static class MyPreprocessor extends Preprocessor { @Override public void process(Document document, PreprocessorReader reader) { // Do something with the reader } } ``` -------------------------------- ### Register and Use a Custom Block Extension in AsciidoctorJ Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-15-to-16.adoc Demonstrates how to register a custom block extension ('yell') and use it within an Asciidoctor document. It shows the conversion process and asserts the expected output. This example requires AsciidoctorJ and Jsoup. ```java Asciidoctor asciidoctor = Asciidoctor.Factory.create(); asciidoctor.javaExtensionRegistry().block("yell", YellStaticBlock.class); final String doc = "[yell]\nHello World"; final String result = asciidoctor.convert(doc, Options.builder().build()); Document htmlDoc = Jsoup.parse(result); assertEquals("HELLO WORLD", htmlDoc.select("p").first().text()); ``` -------------------------------- ### Add Asciidoctor dependency to MANIFEST.MF Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/run-in-wildfly.adoc Example MANIFEST.MF file snippet showing how to declare a dependency on the Asciidoctor module in WildFly. ```plaintext Manifest-Version: 1.0 Dependencies: org.asciidoctor ... ``` -------------------------------- ### YellStaticBlock Extension for AsciidoctorJ 1.6.0 Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-15-to-16.adoc An example implementation of a custom block processor named 'yell' for AsciidoctorJ 1.6.0. It uses annotations to define the context and name, processes lines by converting them to uppercase, and creates a paragraph block. Dependencies include AsciidoctorJ extension interfaces. ```java import org.asciidoctor.ast.ContentModel; import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.extension.BlockProcessor; import org.asciidoctor.extension.Contexts; import org.asciidoctor.extension.Name; import org.asciidoctor.extension.Reader; import java.util.HashMap; import java.util.Map; import static java.util.stream.Collectors.joining; @Contexts(Contexts.PARAGRAPH) @ContentModel(ContentModel.COMPOUND) @Name("yell") public class YellStaticBlock extends BlockProcessor { @Override public Object process(StructuralNode parent, Reader reader, Map attributes) { String upperLines = reader.readLines().stream() .map(String::toUpperCase) .collect(joining("\n")); return createBlock(parent, "paragraph", upperLines, attributes, new HashMap()); } } ``` -------------------------------- ### GET /syntax-highlighter/configuration Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/syntax-highlighting/pages/link-external-resources.adoc Retrieves the current configuration for stylesheet writing capabilities. Checks if the syntax highlighter supports writing external resources to disk. ```APIDOC ## GET /syntax-highlighter/configuration ### Description Checks if the current syntax highlighter implementation supports writing external stylesheets to the filesystem and if it should be enabled based on document requirements. ### Method GET ### Endpoint /syntax-highlighter/configuration ### Response #### Success Response (200) - **writeStylesheetSupported** (boolean) - Indicates if the StylesheetWriter interface is implemented - **shouldWriteStylesheet** (boolean) - Indicates if external resources are needed for the current document #### Response Example { "writeStylesheetSupported": true, "shouldWriteStylesheet": true } ``` -------------------------------- ### Asciidoc content inclusion example Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/asciidoctor-api-options.adoc Shows how to include external Asciidoc content using the include directive. The main document includes content from another Asciidoc file to demonstrate content composition. ```asciidoc = Including content include::includedcontent.adoc[] ``` ```asciidoc This is included content ``` -------------------------------- ### Update AsciidoctorJ Preprocessor for 3.x.x Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/update-preprocessor-api.adoc Example of an updated Preprocessor implementation for AsciidoctorJ 3.0.0 and later. The `process` method now returns a `Reader` object, which can be `null` if no new reader is created. ```java public static class MyPreprocessor extends Preprocessor { @Override public Reader process(Document document, PreprocessorReader reader) { // Do something with the reader return null; } } ``` -------------------------------- ### Convert AsciiDoc using Map collections for configuration Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/conversion-examples.adoc Shows configuration using Map collections for attributes and options. Creates Asciidoctor instance, builds attributes as Map with docbook backend and font icons, creates options Map with in-place setting and attributes, then converts sample.adoc. This approach uses fluent builder API but retrieves configuration as Map objects. ```java Asciidoctor asciidoctor = Asciidoctor.Factory.create(); // <.> Map attributes = Attributes.builder() .backend("docbook") .icons("font") .asMap(); // <.> Map options = Options.builder() .inPlace(true) .attributes(attributes) // <.> .asMap(); // <.> String outfile = asciidoctor.convertFile(new File("sample.adoc"), options); // <.> ---- <.> Create `Asciidoctor` instance. <.> Defines attributes using builder fluent API and retrieves them as `Map`. <.> Registers the attributes map as `attributes`. <.> Converts options to `java.util.Map` instance. ``` -------------------------------- ### Initialize Options using New Builder Pattern Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Recommended new API using Options.builder() to create immutable Options instances with fluent configuration. This pattern provides IDE completion, type safety, and improved readability through indentation. Available from v3.0.x as the primary initialization method. ```java Options options = Options.builder() .backend("html5") .mkDirs(true) .safe(SafeMode.UNSAFE) .build(); ``` -------------------------------- ### Convert AsciiDoc Files to HTML in Java Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt Shows how to convert AsciiDoc files to HTML format with options for output location and safe mode settings. Includes examples for both same-directory and custom-directory outputs. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; import org.asciidoctor.SafeMode; import java.io.File; public class FileConversionExample { public static void main(String[] args) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); try { // Convert file and write to same directory asciidoctor.convertFile( new File("document.adoc"), Options.builder() .toFile(true) // Write output to file .safe(SafeMode.UNSAFE) // Allow file system access .build()); // Convert file and write to specific directory asciidoctor.convertFile( new File("src/docs/document.adoc"), Options.builder() .toFile(true) .toDir(new File("build/docs")) .safe(SafeMode.UNSAFE) .build()); System.out.println("Conversion complete!"); } finally { asciidoctor.shutdown(); } } } ``` -------------------------------- ### Convert AsciiDoc with Java Streams Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt This code demonstrates how to use the Asciidoctor Java library to convert AsciiDoc documents to HTML by leveraging Java's Reader and Writer streams for flexible input and output. The examples show reading from a file and writing to a string, and reading from a string and writing to a file. This approach is useful for integrating AsciiidoctorJ into existing Java I/O workflows. Requires the AsciidoctorJ library. The input and output are handled via streams, and the example does not specify the AsciiDoc content. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; import java.io.*; public class StreamConversionExample { public static void main(String[] args) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); try { // Read from file, write to string try (FileReader reader = new FileReader("document.adoc"); StringWriter writer = new StringWriter()) { asciidoctor.convert(reader, writer, Options.builder().build()); String html = writer.toString(); System.out.println(html); } // Read from string, write to file try (StringReader reader = new StringReader("= Hello\n\nWorld!"); FileWriter writer = new FileWriter("output.html")) { asciidoctor.convert(reader, writer, Options.builder().standalone(true).build()); } System.out.println("Stream conversion complete"); } catch (IOException e) { e.printStackTrace(); } finally { asciidoctor.shutdown(); } } } ``` -------------------------------- ### Declare AsciidoctorJ Dependency in Maven, Gradle, SBT, and Leiningen Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/installation.adoc Demonstrates how to declare the AsciidoctorJ dependency in common build tool configuration files. This allows the build system to automatically download and manage the AsciidoctorJ library. Ensure the correct version is specified for compatibility. ```xml org.asciidoctor asciidoctorj {artifact-version} ``` ```groovy dependencies { compile 'org.asciidoctor:asciidoctorj:{artifact-version}' } ``` ```scala libraryDependencies += "org.asciidoctor" % "asciidoctorj" % "{artifact-version}" ``` ```clojure :dependencies [[org.asciidoctor/asciidoctorj "{artifact-version}"]] ``` -------------------------------- ### Initialize Options using Java Constructor and Setters Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Legacy approach using Options constructor with setter methods to configure backend, safe mode, and directory creation. This pattern allows mutable Options instances that can be modified after initialization. Available since v2.5.x but superseded by builder pattern in v3.0.x. ```java Options options = new Options(); options.setBackend("html5"); options.setSafe(SafeMode.UNSAFE); options.setMkDirs(true); ``` -------------------------------- ### Initialize Options using Map Constructor Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Legacy approach creating Options from a HashMap containing configuration key-value pairs. This pattern supports dynamic option configuration but requires casting and lacks type safety. Available since v2.5.x but superseded by builder pattern in v3.0.x. ```java Map optionsMap = new HashMap<>(); optionsMap.put("backend", "html5"); optionsMap.put("sage", SafeMode.UNSAFE); optionsMap.put("mkdirs", true); Options options = Options(optionsMap); ``` -------------------------------- ### Set Java Flags for JVM Optimization Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/optimization.adoc Configures Java Virtual Machine (JVM) optimization flags for improved start time, specifically targeting Java SE 6. This involves setting the JAVA_OPTS environment variable. ```shell export JAVA_OPTS="-Xverify:none -client" ``` -------------------------------- ### Convert AsciiDoc using Attributes and Options instances Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/conversion-examples.adoc Demonstrates the recommended approach using Asciidoctor, Attributes, and Options classes as instances. Creates an Asciidoctor instance, builds Attributes with docbook backend and font icons, creates Options with in-place conversion enabled, and converts sample.adoc file. This method provides type validation and ease of use. ```java Asciidoctor asciidoctor = Asciidoctor.Factory.create(); // <.> Attributes attributes = Attributes.builder() .backend("docbook") .icons("font") .build(); // <.> Options options = Options.builder() .inPlace(true) .attributes(attributes) .build(); // <.> String outfile = asciidoctor.convertFile(new File("sample.adoc"), options); // <.> ---- <.> Create `Asciidoctor` instance. <.> Defines the attributes as an `Attributes` class. <.> Defines the options as an `Options` class. <.> Converts the document passing previously created `Options` instance. ``` -------------------------------- ### Original YellStaticBlock Extension - AsciidoctorJ 1.5.x Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-15-to-16.adoc Shows the original YellStaticBlock extension implementation for AsciidoctorJ 1.5.x, demonstrating how to create a BlockProcessor that transforms text to uppercase. Uses deprecated AbstractBlock and AbstractNode classes from the AST API. ```java import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.asciidoctor.ast.AbstractBlock; import org.asciidoctor.extension.BlockProcessor; import org.asciidoctor.extension.Reader; import static java.util.stream.Collectors.joining; public class YellStaticBlock extends BlockProcessor { private static Map configs = new HashMap() {{ put("contexts", Arrays.asList(":paragraph")); put("content_model", ":simple"); }}; public YellStaticBlock(String name, Map config) { super(name, configs); } @Override public Object process(AbstractBlock parent, Reader reader, Map attributes) { String upperLines = reader.readLines().stream() // <1> .map(String::toUpperCase) .collect(joining("\n")); return createBlock( // <2> parent, "paragraph", upperLines, attributes, new HashMap<>()); } } ``` -------------------------------- ### Initialize Options using OptionsBuilder Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Legacy fluent API approach using OptionsBuilder to configure Options with method chaining. This pattern provides better readability than constructor/setters but is deprecated in favor of the new builder() method. Available since v2.5.x but superseded by builder pattern in v3.0.x. ```java Options options = OptionsBuilder.options() .backend("html5") .mkDirs(true) .safe(SafeMode.UNSAFE) .get(); ``` -------------------------------- ### Updated YellStaticBlock Extension - AsciidoctorJ 1.6.0 Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-15-to-16.adoc Demonstrates the migrated YellStaticBlock extension for AsciidoctorJ 1.6.0, with updated AST class names (StructuralNode instead of AbstractBlock) and adjusted implementation. Shows the necessary changes for compatibility with the new version. ```java import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.extension.BlockProcessor; import org.asciidoctor.extension.Reader; public class YellStaticBlock extends BlockProcessor { private static Map configs = new HashMap() {{ put("contexts", Arrays.asList(":paragraph")); put("content_model", ":simple"); }}; public YellStaticBlock(String name, Map config) { super(name, configs); } @Override public Object process(StructuralNode parent, Reader reader, Map attributes) { List lines = reader.readLines(); String upperLines = null; for (String line : lines) { if (upperLines == null) { upperLines = line.toUpperCase(); } else { upperLines = upperLines + "\n" + line.toUpperCase(); } } return createBlock(parent, "paragraph", ``` -------------------------------- ### Add AsciidoctorJ EPUB3 Maven Dependency Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/convert-to-epub3.adoc This XML snippet shows how to include the asciidoctorj-epub3 JAR in your Maven project's dependencies. Ensure the version matches the desired Asciidoctor EPUB3 gem version. This dependency is typically scoped to 'runtime'. ```xml org.asciidoctor asciidoctorj-epub3 {asciidoctorj-epub3-version} runtime ``` -------------------------------- ### Ruby Block Extension Implementation Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/ruby-extensions.adoc Provides an example of a Ruby extension class that can be registered with AsciidoctorJ. This specific example implements a block processor that converts paragraph text to uppercase and replaces periods with exclamation marks. ```ruby require 'asciidoctor' require 'asciidoctor/extensions' class YellRubyBlock < Asciidoctor::Extensions::BlockProcessor option :contexts, [:paragraph] option :content_model, :simple def process parent, reader, attributes lines = reader.lines.map {|line| line.upcase.gsub(/\.( |$)/, '!\1') } Asciidoctor::Block.new parent, :paragraph, :source => lines, :attributes => attributes end end ``` -------------------------------- ### Configure Asciidoctor Options (Java) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/extensions/pages/docinfo-processor.adoc Example of configuring Asciidoctor options in Java. This snippet shows how to build an `Options` object, setting `standalone` to `true` and `safe` mode to `SafeMode.SERVER`. These options are crucial for certain extensions, like Docinfo Processors, to function correctly. ```java Options options = Options.builder() .standalone(true) .safe(SafeMode.SERVER) .build(); ``` -------------------------------- ### Load and Parse AsciiDoc in Java Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt This code shows how to load an AsciiDoc string into an Asciidoctor AST (Abstract Syntax Tree) using the Asciidoctor Java library. It demonstrates how to access the document title, navigate the document's structural blocks (like sections), and query the AST for specific types of nodes (like images). This is useful for analyzing document structure without a full conversion. Requires the AsciidoctorJ library. The example content is a simple AsciiDoc string, and the output is the document title, section titles, and a count of image blocks. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; import org.asciidoctor.ast.Document; import org.asciidoctor.ast.Section; import org.asciidoctor.ast.StructuralNode; import java.util.List; import java.util.Map; import java.util.HashMap; public class DocumentLoadingExample { public static void main(String[] args) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); try { String content = "= Document Title\n" + "Author Name\n\n" + "== Section A\n\n" + "First paragraph.\n\n" + "== Section B\n\n" + "image::diagram.png[]\n\n" + "Second paragraph."; // Load document into AST Document document = asciidoctor.load(content, Options.builder().build()); // Access document metadata String title = document.getDoctitle(); System.out.println("Title: " + title); // Navigate document structure List blocks = document.getBlocks(); for (StructuralNode block : blocks) { if (block instanceof Section) { Section section = (Section) block; System.out.println("Section: " + section.getTitle()); } } // Query for specific block types Map selector = new HashMap<>(); selector.put("context", ":image"); List images = document.findBy(selector); System.out.println("Found " + images.size() + " images"); } finally { asciidoctor.shutdown(); } } } ``` -------------------------------- ### Simplified Block Extension Registration in AsciidoctorJ 1.6.0 Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-15-to-16.adoc Illustrates a simplified method for registering a block extension by passing the extension class directly to the registry. The block name is inferred from the @Name annotation within the extension class itself. This requires AsciidoctorJ and Jsoup. ```java Asciidoctor asciidoctor = Asciidoctor.Factory.create(); asciidoctor.javaExtensionRegistry().block(YellStaticBlock.class); // <1> final String doc = "[yell]\nHello World"; final String result = asciidoctor.convert(doc, Options.builder().build()); Document htmlDoc = Jsoup.parse(result); assertEquals("HELLO WORLD", htmlDoc.select("p").first().text()); ``` -------------------------------- ### Set Attributes using Attributes Instance Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Approach for injecting Attributes objects into Options using setAttributes() method. This pattern allows complex attribute configuration through Attributes builder pattern. Supports both legacy and new Options APIs, providing flexibility for attribute management. ```java Attributes attributes = new Attributes(); options.setAttributes(attributes); ``` ```java Attributes attributes = Attributes.builder() .icons("font") .build(); Options options = Options.builder().build(); options.setAttributes(attributes); ``` -------------------------------- ### Update InlineMacroProcessor to Return PhraseNode Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-16-to-20.adoc This code snippet illustrates how to update an `InlineMacroProcessor` for AsciidoctorJ 2.0.x. Previously, it returned a String; now, it must return a `PhraseNode` using the `createPhraseNode` method to avoid logging warnings and ensure correct substitution. ```java public class YellMacroProcessor extends InlineMacroProcessor { public YellMacroProcessor(String macroName, Map config) { super(macroName, config); } @Override public Object process(ContentNode parent, String target, Map attributes) { return target.toUpperCase(); } } ``` ```java public class YellMacroProcessor extends InlineMacroProcessor { public YellMacroProcessor(String macroName, Map config) { super(macroName, config); } @Override public Object process(ContentNode parent, String target, Map attributes) { return createPhraseNode(parent, "quoted", target.toUpperCase(), attributes, new HashMap<>()); } } ``` -------------------------------- ### Example Asciidoc with Positional Attributes Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/extensions/pages/inline-macro-processor.adoc This Asciidoc snippet showcases the usage of an inline macro that utilizes positional attributes as defined by a corresponding Java processor. It demonstrates how to invoke the macro with arguments that are interpreted based on their position. ```asciidoc include::example$issue-inline-macro-positional.adoc[] ``` -------------------------------- ### Convert AsciiDoc to EPUB3 using AsciidoctorJ Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/convert-to-epub3.adoc This Java code demonstrates converting an AsciiDoc file to EPUB3 format using AsciidoctorJ. It sets the backend to 'epub3' and uses SAFE mode. The conversion requires a specific file structure for the input AsciiDoc documents. ```java asciidoctor.convertFile(new File("spine.adoc"), Options.builder().safe(SafeMode.SAFE).backend("epub3").build()); // <1> <2> assertThat(new File("target/test-classes/index.epub").exists(), is(true)); ``` -------------------------------- ### Update Extension Registry Service File Location Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-16-to-20.adoc This shows the change in the service file path required for automatic extension discovery. The file `META-INF/services/org.asciidoctor.extension.spi.ExtensionRegistry` needs to be renamed to `META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry` to match the updated package. ```text ./META-INF/services/org.asciidoctor.extension.spi.ExtensionRegistry ``` ```text ./META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry ``` -------------------------------- ### Convert methods using Options in Java Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-asciidoctor.adoc Migrate deprecated convert methods to use the modern org.asciidoctor.Options. These examples show conversions from strings and files, writer rendering, and typed results using Options. This API is available in AsciidoctorJ v3.0.0+. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; import org.asciidoctor.OptionsBuilder; Asciidoctor asciidoctor = Asciidoctor.Factory.create(); // Convert a String to HTML using Options String html = asciidoctor.convert( "= Hello\nThis is AsciiDoc", Options.builder().option("backend", "html5").build() ); // Convert a File using Options String html2 = asciidoctor.convertFile( "doc.adoc", Options.builder().option("backend", "html5").build() ); // Render into a Writer using Options java.io.StringWriter writer = new java.io.StringWriter(); asciidoctor.convert( new java.io.StringReader("= Title\nContent"), writer, Options.builder().option("backend", "html5").build() ); // Convert with typed result using Options String json = asciidoctor.convert( "= Doc\n:doctype: docbook\n", Options.builder().option("backend", "docbook5").build(), String.class ); // Convert a File to a typed result using Options String xml = asciidoctor.convertFile( "article.adoc", Options.builder().option("backend", "docbook5").build(), String.class ); // Convert multiple files to results using Options String[] results = asciidoctor.convertFiles( java.util.Arrays.asList(new java.io.File("a.adoc"), new java.io.File("b.adoc")), Options.builder().option("backend", "html5").build() ); // Old deprecated signatures (removed) - do not use: // asciidoctor.convert(String content, Map options); // asciidoctor.convert(String content, OptionsBuilder options); // asciidoctor.convertFile(File file, Map options); // asciidoctor.convertFile(File file, OptionsBuilder options); // T convert(String content, Map options, Class expectedResult); // T convert(String content, OptionsBuilder options, Class expectedResult); // void convert(Reader contentReader, Writer rendererWriter, Map options); // void convert(Reader contentReader, Writer rendererWriter, OptionsBuilder options); // String[] convertDirectory(Iterable directoryWalker, Map options); // String[] convertDirectory(Iterable directoryWalker, OptionsBuilder options); // String[] convertFiles(Collection files, Map options); // String[] convertFiles(Collection files, OptionsBuilder options); ``` -------------------------------- ### Set Attributes using Map Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Approach for injecting attributes as Map into Options using setAttributes() method. This pattern supports dynamic attribute configuration but lacks type safety. Available for both legacy and new Options APIs, providing backward compatibility. ```java Map attributesMap = new HashMap<>(); attributesMap.put("toclevels", 2); attributesMap.put("icons", "font"); options.setAttributes(attributesMap); ``` -------------------------------- ### Locate AsciiDoc Files with AsciiDocDirectoryWalker (Java) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/locating-files.adoc Uses AsciiDocDirectoryWalker to find all AsciiDoc files (.adoc, .ad, .asciidoc, .asc) within a specified root directory and its subfolders, ignoring files starting with an underscore. It returns a List of found files. ```java import java.util.List; import org.asciidoctor.AsciiDocDirectoryWalker; DirectoryWalker directoryWalker = new AsciiDocDirectoryWalker("docs"); // <1> List asciidocFiles = directoryWalker.scan(); // <2> ``` -------------------------------- ### Update Extension Registry Interface and Service File Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/extension-migration-guide-16-to-20.adoc This snippet demonstrates the necessary changes to the Java implementation and the service file for registering extensions automatically. The primary change is updating the import statement for `ExtensionRegistry` and renaming the service file to reflect the new package structure. ```java package com.example; import org.asciidoctor.extension.spi.ExtensionRegistry; public class MyExtension implements ExtensionRegistry { @Override public void register(Asciidoctor asciidoctor) { JavaExtensionRegistry javaExtensionRegistry = asciidoctor.javaExtensionRegistry(); javaExtensionRegistry.treeprocessor(MyTreeprocessor.class); } } ``` ```java package com.example; import org.asciidoctor.jruby.extension.spi.ExtensionRegistry; // <1> public class MyExtension implements ExtensionRegistry { @Override public void register(Asciidoctor asciidoctor) { JavaExtensionRegistry javaExtensionRegistry = asciidoctor.javaExtensionRegistry(); javaExtensionRegistry.treeprocessor(MyTreeprocessor.class); } } ``` -------------------------------- ### Custom Logging in Java Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt This Java example shows how to implement a custom log handler to capture Asciidoctor messages during document conversion. It depends on AsciidoctorJ logging classes and processes AsciiDoc content, outputting errors and collecting log records. The approach collects logs in a list for later inspection but requires manual unregistering of handlers. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; import org.asciidoctor.log.LogHandler; import org.asciidoctor.log.LogRecord; import org.asciidoctor.log.Severity; import java.util.ArrayList; import java.util.List; public class CustomLoggingExample { static class CollectingLogHandler implements LogHandler { private List logRecords = new ArrayList<>(); @Override public void log(LogRecord logRecord) { logRecords.add(logRecord); System.err.println( logRecord.getSeverity() + ": " + logRecord.getMessage() + " [" + logRecord.getSourceLocation() + "]" ); } public List getLogRecords() { return logRecords; } } public static void main(String[] args) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); CollectingLogHandler logHandler = new CollectingLogHandler(); try { // Register log handler asciidoctor.registerLogHandler(logHandler); // Convert content with invalid syntax String content = "= Document\n\n" + "include::missing-file.adoc[]\n\n" + "{undefined-attribute}"; String result = asciidoctor.convert( content, Options.builder().standalone(false).build()); // Check collected logs System.out.println("\nCollected " + logHandler.getLogRecords().size() + " log messages"); for (LogRecord record : logHandler.getLogRecords()) { if (record.getSeverity() == Severity.ERROR) { System.out.println("ERROR: " + record.getMessage()); } } // Unregister when done asciidoctor.unregisterLogHandler(logHandler); } finally { asciidoctor.shutdown(); } } } ``` -------------------------------- ### Set Attributes using OptionsBuilder Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-methods-in-options.adoc Legacy OptionsBuilder approach for setting attributes during Options creation using attributes() method. This pattern supports three attribute injection types: Attributes instance, Map, and AttributesBuilder. Deprecated in favor of new builder pattern available from v3.0.x. ```java Attributes attributes = new Attributes(); Options options = OptionsBuilder.options() .attributes(attributes) .get(); ``` ```java Map attributesMap = new HashMap<>(); attributesMap.put("toclevels", 2); attributesMap.put("icons", "font"); Options options = OptionsBuilder.options() .attributes(attributesMap) .get(); ``` ```java AttributesBuilder attributesBuilder = AttributesBuilder.attributes(); Options options = OptionsBuilder.options() .attributes(attributesBuilder) .get(); ``` ```java Attributes attributes = Attributes.builder() .icons("font") .build(); Options options = Options.builder() .attributes(attributes) .build(); ``` -------------------------------- ### Create SPI Configuration File for SyntaxHighlighterRegistry Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/syntax-highlighting/pages/automatic-loading.adoc This configuration file specifies the fully qualified name of the SyntaxHighlighterRegistry implementation. It must be placed in META-INF/services for the SPI mechanism to work. ```java include::example$syntaxhighlighterregistry/META-INF/services/org.asciidoctor.jruby.syntaxhighlighter.spi.SyntaxHighlighterRegistry[] ``` -------------------------------- ### Create Asciidoctor module descriptor for WildFly Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/run-in-wildfly.adoc XML configuration for defining an Asciidoctor module in WildFly, specifying resource paths and dependencies including JRuby and SLF4J. ```xml ``` -------------------------------- ### Load AsciiDoc document in Java Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/read-document-tree.adoc Demonstrates how to load an AsciiDoc document into a Document object using AsciidoctorJ. The example shows loading from a string and retrieving the document title. ```java import org.asciidoctor.ast.Document; //... Document document = asciidoctor.load(DOCUMENT, Options.builder().build()); assertThat(document.doctitle(), is("Document Title")); ``` -------------------------------- ### Query document blocks in Java Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/read-document-tree.adoc Illustrates how to query specific blocks (like images) from a document using a map selector. The example finds all image blocks and verifies the count. ```java Document document = asciidoctor.load(DOCUMENT, Options.builder().build()); Map selector = new HashMap<>(); selector.put("context", ":image"); List findBy = document.findBy(selector); assertThat(findBy, hasSize(2)); ``` -------------------------------- ### Retrieve document sections in Java Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/read-document-tree.adoc Shows how to access and cast sections from a loaded AsciiDoc document. Includes examples of checking section properties like index, sectname, and special status. ```java import org.asciidoctor.ast.Document; import org.asciidoctor.ast.Section; //... Document document = asciidoctor.load(DOCUMENT, Options.builder().build()); Section section = (Section) document.getBlocks().get(1); assertThat(section.index(), is(0)); assertThat(section.sectname(), is("sect1")); assertThat(section.special(), is(false)); ``` -------------------------------- ### Create Asciidoctor Instance (Java) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/asciidoctor-interface.adoc Demonstrates how to create an Asciidoctor instance using the default factory method. This method is typically used when extensions are already on the classpath. Requires the AsciidoctorJ library. ```java include::example$org/asciidoctor/integrationguide/AsciidoctorInterface.java[tags=create] ``` -------------------------------- ### Implement Prism.js Highlighter in Java Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/syntax-highlighting/pages/static-during-conversion.adoc This Java code implements the `Highlighter` interface to integrate Prism.js for static syntax highlighting. It uses the Nashorn JavaScript engine to invoke Prism.js during AsciidoctorJ conversion. The `highlight()` method converts source text to static HTML with CSS classes. It handles CSS inclusion either as a separate file or embedded within a style tag. ```java package org.asciidoctor.integrationguide.syntaxhighlighter; import org.asciidoctor.ast.Cursor; import org.asciidoctor.ast.StructuralNode; import org.asciidoctor.syntaxhighlighter.HighlightResult; import org.asciidoctor.syntaxhighlighter.Highlighter; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; import java.net.URL; import java.util.Map; public class PrismJsHighlighter implements Highlighter { private final ScriptEngine engine; private final String prismJsPath; private final String prismJsCss; public PrismJsHighlighter(String prismJsPath, String prismJsCss) { this.prismJsPath = prismJsPath; this.prismJsCss = prismJsCss; ScriptEngineManager manager = new ScriptEngineManager(); this.engine = manager.getEngineByName("nashorn"); try { this.engine.eval(new FileReader(prismJsPath)); } catch (Exception e) { throw new RuntimeException("Failed to load Prism.js", e); } } @Override public HighlightResult highlight(StructuralNode parent, String src, String lang, Map options) { Invocable invocable = (Invocable) this.engine; try { Object html = invocable.invokeFunction("highlight", src, lang); return new HighlightResult(html.toString(), ""); } catch (Exception e) { throw new RuntimeException("Failed to highlight source", e); } } public static void main(String[] args) throws Exception { // Example usage: PrismJsHighlighter highlighter = new PrismJsHighlighter("path/to/prism.js", "/* prism.css content */"); StructuralNode dummyNode = null; String sourceCode = "System.out.println(\"Hello World!\");"; String language = "java"; Map options = Map.of(); HighlightResult result = highlighter.highlight(dummyNode, sourceCode, language, options); System.out.println("Highlighted HTML: " + result.getHtml()); System.out.println("CSS: " + result.getCss()); } } ``` -------------------------------- ### Create Asciidoctor Instance in Java Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt Demonstrates how to create an Asciidoctor instance using the Java ServiceLoader pattern. The instance is used for document conversions and must be properly shut down to release resources. ```java import org.asciidoctor.Asciidoctor; public class AsciidoctorExample { public static void main(String[] args) { // Create Asciidoctor instance Asciidoctor asciidoctor = Asciidoctor.Factory.create(); try { // Use the instance for conversions String result = asciidoctor.convert("= Hello World\n\nThis is AsciiDoc.", org.asciidoctor.Options.builder().build()); System.out.println(result); } finally { // Clean up resources when done asciidoctor.shutdown(); } } } ``` -------------------------------- ### Convert AsciiDoc Strings to HTML in Java Source: https://context7.com/asciidoctor/asciidoctorj/llms.txt Illustrates conversion of AsciiDoc string content to both full HTML documents and embeddable HTML fragments. Shows how to control standalone vs fragment output using options. ```java import org.asciidoctor.Asciidoctor; import org.asciidoctor.Options; public class StringConversionExample { public static void main(String[] args) { Asciidoctor asciidoctor = Asciidoctor.Factory.create(); try { String asciidocContent = "= Document Title\n\n" + "== Section 1\n\n" + "This is a paragraph with *bold* and _italic_ text.\n\n" + "[source,java]\n" + "----\n" + "System.out.println(\"Hello\");\n" + "----"; // Convert to standalone HTML document String htmlFull = asciidoctor.convert( asciidocContent, Options.builder() .standalone(true) // Include HTML header/footer .build()); // Convert to embeddable HTML fragment String htmlFragment = asciidoctor.convert( asciidocContent, Options.builder() .standalone(false) // No header/footer .build()); System.out.println("Full HTML:\n" + htmlFull); System.out.println("\nFragment:\n" + htmlFragment); } finally { asciidoctor.shutdown(); } } } ``` -------------------------------- ### Obtain backing Map for OptionsBuilder (Java) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/partials/removal-of-deprecated-asMap-from-builders.adoc Demonstrates how to get the backing `Map` for `OptionsBuilder` using the `asMap()` method. This method was available in AsciidoctorJ v2.5.x. It takes builder configurations and returns a map representation. ```java Map optionsMap = Options.builder() .backend("html5") .mkDirs(true) .safe(SafeMode.UNSAFE) .asMap(); ``` -------------------------------- ### Running AsciidoctorJ with Extension (Command Line) Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/extensions/pages/register-extensions-automatically.adoc Shows how to execute AsciidoctorJ with a custom extension JAR on the classpath. This involves providing the classpath to the `asciidoctorj` command or using a Java command with the necessary JAR files. ```bash asciidoctorj -cp=lib/myextension.jar test.adoc ``` ```bash java -cp lib/jruby-complete-{jruby-version}.jar;lib/asciidoctor-api-{artifact-version}.jar;lib/asciidoctor-core-{artifact-version}.jar;lib/jcommander-{jcommander-version}.jar;lib/myextension.jar org.asciidoctor.cli.jruby.AsciidoctorInvoker test.adoc ``` -------------------------------- ### Initialize Attributes using Builder Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/ROOT/pages/asciidoctor-api-options.adoc Demonstrates initializing Asciidoctor document attributes using the `Attributes.builder()` fluent API. This method supports setting individual attributes, enabling experimental features, and passing multiple arguments as a String or String array. It is the recommended approach for attribute configuration. ```java Attributes attributes = Attributes.builder() .icons("font") .experimental(true) .attribute("my-attribute", "my-value") .build(); ``` ```java Attributes attributes = Attributes.builder().arguments("toc numbered").build(); ``` ```java String[] attributesArray = new String[]{"toc", "source-highlighter=coderay"}; Attributes attributes = Attributes.builder().arguments(attributesArray).build(); ``` -------------------------------- ### Configure Maven Repository for AsciidoctorJ Pre-release Source: https://github.com/asciidoctor/asciidoctorj/blob/main/docs/modules/guides/pages/use-prerelease-version.adoc This snippet shows how to configure a Maven repository to access pre-release versions of AsciidoctorJ. The repository URL varies per build and is available at oss.sonatype.org. This configuration enables access to the latest pre-release artifacts. ```xml staging https://oss.sonatype.org/content/repositories/orgasciidoctor-1234 <1> true ```