How to Enable Syntax Highlighting in Code Examples - Fluid Topics - Latest

Category
How To
Audience
public
Version
Latest

Business need

Code samples in technical documentation are easier to read if syntax is correctly highlighted.

Overview of the solution

Automatically highlighting codeblocks on Fluid Topics depends on the publication format.

PORTAL_ADMIN and ADMIN users can style:

Procedure

DITA

To apply syntax highlighting to codeblocks in DITA content:

  1. Give <codeblock> elements the following attribute:

    outputclass="ft-code-highlight language-XXX"
    
  2. Replace XXX by the alias for the programming language in the codeblock.

    For example, for Python code, add:

    <codeblock outputclass="ft-code-highlight language-python">
    # This program adds two numbers
    
    num1 = 1.5
    num2 = 6.3
    
    # Add two numbers
    sum = num1 + num2
    
    # Display the sum
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
    </codeblock>
    

Markdown

Fluid Topics automatically applies classes to distinct sections of code within fenced code blocks in Markdown content.

Users can then style the classes to match the look of their portal.

  1. Copy the following codeblock:

    /* Color variables */
    @hl-primary-color: #a31515;
    @hl-secondary-color: #0000ff;
    @hl-background: #ffffff;
    @hl-comments: #008000;
    
    .highlight .hll { background-color: @hl-background }
    .highlight { background: @hl-background; }
    .highlight .c { color: @hl-comments } /* Comment */
    .highlight .k { color: @hl-secondary-color } /* Keyword */
    .highlight .ch { color: @hl-comments } /* Comment.Hashbang */
    .highlight .cm { color: @hl-comments } /* Comment.Multiline */
    .highlight .cp { color: @hl-secondary-color } /* Comment.Preproc */
    .highlight .cpf { color: @hl-comments } /* Comment.PreprocFile */
    .highlight .c1 { color: @hl-comments } /* Comment.Single */
    .highlight .cs { color: @hl-comments } /* Comment.Special */
    .highlight .ge { font-style: italic } /* Generic.Emph */
    .highlight .gh { font-weight: bold } /* Generic.Heading */
    .highlight .gp { font-weight: bold } /* Generic.Prompt */
    .highlight .gs { font-weight: bold } /* Generic.Strong */
    .highlight .gu { font-weight: bold } /* Generic.Subheading */
    .highlight .kc { color: @hl-secondary-color } /* Keyword.Constant */
    .highlight .kd { color: @hl-secondary-color } /* Keyword.Declaration */
    .highlight .kn { color: @hl-secondary-color } /* Keyword.Namespace */
    .highlight .kp { color: @hl-secondary-color } /* Keyword.Pseudo */
    .highlight .kr { color: @hl-secondary-color } /* Keyword.Reserved */
    .highlight .kt { color: #2b91af } /* Keyword.Type */
    .highlight .s { color: #a31515 } /* Literal.String */
    .highlight .nc { color: #2b91af } /* Name.Class */
    .highlight .ow { color: @hl-secondary-color } /* Operator.Word */
    .highlight .sa { color: @hl-primary-color } /* Literal.String.Affix */
    .highlight .sb { color: @hl-primary-color } /* Literal.String.Backtick */
    .highlight .sc { color: @hl-primary-color } /* Literal.String.Char */
    .highlight .dl { color: @hl-primary-color } /* Literal.String.Delimiter */
    .highlight .sd { color: @hl-primary-color } /* Literal.String.Doc */
    .highlight .s2 { color: @hl-primary-color } /* Literal.String.Double */
    .highlight .se { color: @hl-primary-color } /* Literal.String.Escape */
    .highlight .sh { color: @hl-primary-color } /* Literal.String.Heredoc */
    .highlight .si { color: @hl-primary-color } /* Literal.String.Interpol */
    .highlight .sx { color: @hl-primary-color } /* Literal.String.Other */
    .highlight .sr { color: @hl-primary-color } /* Literal.String.Regex */
    .highlight .s1 { color: @hl-primary-color } /* Literal.String.Single */
    .highlight .ss { color: @hl-primary-color } /* Literal.String.Symbol */
    .highlight .mi { color: @tertiary } /* Numbers */
    

    Other predefined styles are available in the pygments-css GitHub repository.

  2. Go to Administration, Portal, and open the Content styles menu.

  3. In the Topic Styles field, paste the CSS styles.
  4. Adapt the styles to the portal's appearance.
  5. Select Save.
  6. In a Markdown file, add a fenced codeblock, and specify a language.

    For example:

    ```json
    {
      "message" : "This is my feedback message",
      "from" : "jdoe@example.com"
    }
    ```
    
  7. Publish the document.

The resulting codeblock is the following:

{
  "message" : "This is my feedback message",
  "from" : "jdoe@example.com"
}

HTML

For formats other than Markdown, if it is possible to insert raw HTML, add an <ft-code-highlight> element.

For example:

<ft-code-highlight language="javascript" theme="sunburst">console.log("Hello world!")</ft-code-highlight>

The language attribute is mandatory, while the theme attribute is optional. The default theme value is monokai.

  • Go to the highlight.js Demo to try other themes.
  • To style codeblocks automatically, it may be possible to use Custom JavaScript.
  • It is possible to use the <ft-code-highlight> element and to add a copy to clipboard button in codeblocks.
  • Use the --ft-code-highlight-background-color CSS property to change the background of the <ft-code-highlight> element. For example:

    ft-code-highlight {
      --ft-code-highlight-background-color: red;
    }
    

Combine syntax highlighting and copy to clipboard button

It is possible to combine the syntax highlighting and copy to clipboard button by following the procedure below:

  1. Add the <div class="ft-copy-block"> element before the <ft-code-highlight> element.

  2. Add the <pre> element at the beginning of the codeblock without adding any space for codeblocks with multiple lines.

Example

<div class="ft-copy-block">
  <ft-code-highlight language="javascript" theme="sunburst">
  <pre>{
    console.log("Hello, World!");
    function greet(name) {
    console.log(`Hello, ${name}!`);}
    }    
  </ft-code-highlight>
</div>

Result

{
    console.log("Hello, World!");
    function greet(name) {
    console.log(`Hello, ${name}!`);}
    }    
  

Paligo

To apply syntax highlighting to codeblocks in Paligo content:

  1. Give <programlisting> elements the following attribute:

    role="ft-code-highlight language-XXX"
    
  2. Replace XXX by the alias for the programming language in the codeblock.

    For example, for Python code, add:

    <programlisting role="ft-code-highlight language-python">
    # This program adds two numbers
    
    num1 = 1.5
    num2 = 6.3
    
    # Add two numbers
    sum = num1 + num2
    
    # Display the sum
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
    </programlisting>
    

JavaScript

Highlighting code is possible by using the HighlightJS library.

  • This method does not apply in designed pages by default. To integrate syntax highlighting in designed pages, get in touch with a Fluid Topics representative.
  • Adding custom JavaScript code requires technical skills, and remains under the responsibility of the customer. Antidot does not accept responsibility for any service malfunction related to JavaScript customization.
  1. Copy the following codeblock:

    const initHighlightJS = () => {
      // Highlight JS
      let hljsScriptLoaded = false;
      document.addEventListener("ft:reader:topicsloaded", () => {
        if (!hljsScriptLoaded) {
          var hljsScript = document.createElement("script");
          hljsScript.src =
            "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js";
          hljsScript.async = true;
          hljsScript.onload = function () {
            document
              .querySelectorAll("pre.codeblock p, pre.codeblock, div.highlight pre, pre")
              .forEach((block) => {
                hljs.highlightBlock(block);
              });
          };
          document.head.appendChild(hljsScript);
    
          var hljsStyle = document.createElement("link");
          hljsStyle.href =
            "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css";
          hljsStyle.rel = "stylesheet";
          document.head.appendChild(hljsStyle);
          hljsScriptLoaded = true;
        }
      });
    };
    
    initHighlightJS();
    

    The purpose of the document.querySelectorAll method is to match the HTML elements, IDs, and classes of codeblocks to highlight. Those elements, IDs, and classes may differ depending on the publication format. PORTAL_ADMIN and ADMIN users must adapt the content of document.querySelectorAll to match the codeblocks on a portal.

  2. Go to Administration, Portal, and open the Custom JavaScript menu.

  3. Paste the JavaScript code.
  4. Select Save.

Code blocks are now correctly highlighted.

Example

The HighlightJS library offers a demo where users can insert code, and see how the library would highlight it.