Source Code Blocks

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, Asciidoctor integrates with a number of libraries to syntax highlight the source code blocks in your document. The list of integrated libraries includes Rouge, CodeRay, Pygments, and highlight.js.

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 doucment 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
[source,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.