Source Code Blocks

A source block is a specialization of a listing block. Developers are accustomed to seeing source code colorized to emphasize the code’s structure (i.e., keywords, types, delimiters, etc.). This technique is known as syntax highlighting. Since this technique is so prevalent, AsciiDoc processors will integrate at least one library to syntax highlight the source code blocks in your document. For example, Asciidoctor provides integration with Rouge, CodeRay, Pygments, and highlight.js, as well as an adapter API to add support for additional libraries.

Example 1 shows a listing block with the source style and language ruby applied to its content, hence a source block.

Example 1. Source block syntax
[source,ruby]
----
require 'sinatra'

get '/hi' do
  "Hello World!"
end
----

The result of Example 1 is rendered below.

require 'sinatra'

get '/hi' do
  "Hello World!"
end

Since a source block is most often used to designate a block with source code of a particular language, the source style itself is optional. The mere presence of the language on a listing block automatically promotes it to a source block.

Example 2 shows a listing block implied to be a source block because a language is specified.

Example 2. Implied source block
[,ruby]
----
require 'sinatra'

get '/hi' do
  "Hello World!"
end
----

This shorthand also works if the source-language attribute is set on the document, which serves as the default language for source blocks. If the source-language attribute is set on the document and you want to make a regular listing block, add the listing style to the block.

Using include directives in source blocks

You can use an include directive to insert source code into an AsciiDoc document directly from a file.

Example 3. Code inserted from another file
[,ruby]
----
include::app.rb[]
----
If you specify custom substitutions on the source block using the subs attribute, make sure to include the specialcharacters substitution if you want to preserve syntax highlighting. However, if you do plan to modify the substitutions, we recommend using incremental substitutions instead.