home

PDF letter size

How to do code syntax highlighting in HTML

Nasser M. Abbasi

September 8, 2023   Compiled on September 8, 2023 at 9:55am

This small note to document steps for code highlighting in HTML. There are many ways to do this, but these are the steps that works for me.

  1. Downloaded highlight.js from http://highlightjs.readthedocs.io extrated.
  2. Download highlightjs-line-numbers.js-master.zip.zip from

    https://github.com/wcoder/highlightjs-line-numbers.js/

    which adds line number to highlight.js since highlight.js does not support line numbers.

  3. Add these lines to the HTML page head section (change path as needed) per instructions in the reference below.

    <style> 
    .hljs-line-numbers { 
        text-align: right; 
        border-right: 1px solid #ccc; 
        color: #999; 
        -webkit-touch-callout: none; 
        -webkit-user-select: none; 
        -khtml-user-select: none; 
        -moz-user-select: none; 
        -ms-user-select: none; 
        user-select: none; 
    } 
    </style> 
    <link rel="stylesheet" type="text/css" href="index.css" /> 
    <link rel="stylesheet" href="/styles/highlight/styles/default.css"> 
    <script src="/styles/highlight/highlight.pack.js"></script> 
    <script src="/styles/highlightjs-line-numbers.js-master/src/highlightjs-line-numbers.js"> 
    </script> 
    <script>hljs.initHighlightingOnLoad();</script> 
    <script>hljs.initLineNumbersOnLoad();</script>
     
    
  4. Add the code itself

    <pre><code class="Matlab"> 
      code here.... 
    </code></pre>
     
    
  5. That is all. But remember to access the file via a web server with the above path as in http://localhost/magine/foo3.html where the HTML page is located in some folder called magine under public_html/.

References:

GNU Source-highlight

https://highlightjs.org/

https://github.com/wcoder/highlightjs-line-numbers.js/ Add line numbers to highlightjs

syntax highlighter 4.0

syntax highlighter 3.0.8

list of languages supported

How to make new brush