Edit online

Code blocks are used to render section of programming code.

Edit online

This topic refers only to the DITA Map PDF - based on HTML5 & CSS transformation type.

You can use syntax highlighting to make it easier to read your code snippets by displaying each type of code in different colors and fonts. In the DITA topics, set the @outputclass attribute on the <codeblock> elements to one of these values:

  • language-bourne
  • language-c
  • language-cpp
  • language-csharp
  • language-css
  • language-ini
  • language-java
  • language-javascript
  • language-json
  • language-lua
  • language-perl
  • language-php
  • language-python
  • language-ruby
  • language-sql
  • language-xml

For example, for a java snippet:

<codeblock outputclass="language-java">
   for (int i=0; i &lt;100; i++) {
     // do something
   }
</codeblock>

The resulting HTML fragment in the merged HTML5 document is:

 <pre class="+ topic/pre pr-d/codeblock pre codeblock language-java" 
    xml:space="preserve">
   <strong class="hl-keyword" style="color:#7f0055">for</strong> 
       (<strong class="hl-keyword" style="color:#7f0055">int</strong> 
         i=<span class="hl-number">0</span>; i 
            &lt;<span class="hl-number">100</span>; i++) {
     <em class="hl-comment" style="color:#006400">// do something</em>
   }
</pre>

And in the output, it will be rendered as:

java code sample coloring

Changing the Colors for the Syntax Highlighting

As you can see in the above example, the HTML elements <span> and <strong> are used to color the content. Since they have a @style attribute set, the overriding properties need to be marked with !important.

Suppose you want to color the keywords in red and the comments in blue. To do so, add the following to your customization CSS:

.hl-keyword {
  color: red !important;
}
.hl-comment {
  color: blue !important;
}

Edit online

By default, code blocks have the content wrapped to avoid the bleeding of long lines out of the page. To avoid wrapping, add the following in your customization CSS:

*[class~="pr-d/codeblock"] {
   white-space: pre;
}

For the DITA Map PDF - based on HTML5 & CSS transformation type, the best solution to distinguish between lines is to leave them wrapped, but color each line with a different background (zebra coloring). An example is provided here: XSLT Extensions for PDF Transformations.