documentationliterate-programmingasciidoc

How to include code excerpts using tags in asciidoc?


I can include the full Greet.java file

public class Greet {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

from within the asciidoc file

== Hello Java
This is how one greets in Java:

[source,java]
.Greet.java
----
include::Greet.java
----

producing the documentation

adocked-greet-java1.png

But suppose that I only want to include an excerpt from the code delimited by tags. In the code above, suppose I only want to include the main function.

I don't see symbolic tags in the documentation, but this page suggests that it's sufficient to write

public class Greet {
    // tag::helloMethod[]
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
    // end::helloMethod[]
}

and

== Hello Java
This is how one greets in Java:

[source,java]
.Greet.java
----
include::Greet.java[tags=helloMethod]
----

That just produces:

adocked-greet-java2.png

Can you suggest a method that would include just the excerpt? I'm using asciidoc 8.6.9.


Solution

  • What you're doing should work fine in Asciidoctor (the Ruby implementation of AsciiDoc), but not AsciiDoc (the Python implementation).

    Notice though the different mechanism for obtaining syntax highlighting.

    To get syntax highlighting with asciidoc one uses a command-line switch asciidoc -a source-highlighter=pygments file.adoc.

    No command-line switch is needed (or possible) with Asciidoctor. With AsciiDoctor syntax highlighting is obtained by:

    1. Inserting :source-highlighter: pygments at the top of each source file, and
    2. Running sudo gem install pygments.rb to install pygments.