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>
    

It is possible to combine the ft-copy-block and ft-code-highlight output classes by placing ft-copy-block before ft-code-highlight. For example:

<codeblock outputclass="ft-copy-block ft-code-highlight language-xml">console.log("Hello, World!");</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 example:

    /* 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 is possible to use 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. The method depends on whether the portal has a designed or classic Reader page.

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

Designed reader page

  • This method only applies in designed Reader pages.
  • Adding a Topic content script 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. Use a text editor to create a .js file, and name it highlighting.js, for example.
  2. Copy and paste the following example in the file:

    export default async function highlighting({ container }) {
      const codeblocks = container.querySelectorAll(
        "pre.codeblock p, pre.codeblock, div.highlight pre, pre",
      );
    
      await loadExternalScript(
        "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js",
      );
    
      if (!document.getElementById("hljs-theme")) {
        const themeLink = document.createElement("link");
        themeLink.id = "hljs-theme";
        themeLink.rel = "stylesheet";
        themeLink.href =
          "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css"; // Change URL for different theme
        container.appendChild(themeLink);
      }
    
      codeblocks.forEach((codeblock) => {
        window.hljs.highlightElement(codeblock);
      });
    }
    

    See highlight.js' Examples for different themes. To change the highlighting style, change the themeLink.href URL to another style's URL. To find one, look at URLs containing /styles/.

    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.

  3. Go to the Administration menu, and select the Design section.

  4. In the Reader tab, go to the Topic templates section and select the topic template used for the designed Reader page.
  5. Select the Topic content component, and select the Settings tab.
  6. Select Add script, then New script.
  7. Upload the highlighting.js file.
  8. Select OK, then select Save.

Code blocks are now correctly highlighted.

Classic reader page

  • This method only applies in the classic Reader page.
  • 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 example:

    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.