Syntax Highlighting

A Personalized Coding Experience

Custom Syntax Highlighting

I have developed a custom syntax highlighting scheme, inspired by my personal Vim theme, that I use every day. This project was born from a desire to enhance code readability and maintain consistency with the aesthetics of my preferred working environment.

The syntax highlighter integrates seamlessly with these languages below, offering a clear and concise visual representation of code structure and elements. This effort reflects my continuous pursuit of a more efficient and visually appealing coding experience.

Compiled & Scripting Languages

C / C++

Fortran

Python

Matlab / Octave

CMake

Reverse Polish LISP (RPL)

Web & Markup Languages

HTML

JavaScript

CSS

JSON

Embedded JavaScript

Compiled & Scripting Languages

C / C++

Below is an example of C:


/*
   Program to calculate the factorial of a number recursively
*/

#include <stdio.h>

// Recursive function to compute factorial
int factorial(int n) {
    if (n == 0) return 1; // Case: 0! = 1
    return n * factorial(n - 1); // Recursive call
}

int main() {
    int num = 5;
    printf("Factorial of %d is %d\n", num, factorial(num)); // Print the result
    return 0;
}
  

Below is an example of C++:


/*
   Class-based example:
   A demonstration of encapsulation with getter / setter methods
*/

#define ST_D(x) static_cast<double>(x)

#include <iostream>
using namespace std;

class Rectangle {
private:
    int mLength, mWidth; // Dimensions

public:
    // Initialize dimensions
    Rectangle(int length, int width) : mLength(length), mWidth(width) {}

    // Length setter
    void SetLength(int length) {
        mLength = length;
    }

    // Area getter
    int GetArea() const {
        return mLength * mWidth; // Area = length * width
    }
};

int main() {
    Rectangle rect(10, 5); // Create a rectangle object
    cout << "Area: " << rect.GetArea() << endl; // Output the area
    rect.SetLength(15); // Change the length
    cout << "Updated Area: " << ST_D(rect.GetArea()) << endl; // Output the updated area
    return 0;
}
#undef ST_D
  

Fortran

Below is an example of Fortran:


C
C CALCULATE THE SUM OF AN ARRAY USING A LOOP
C

PROGRAM SUMARRAY
    INTEGER :: I, N, SUM
    INTEGER, DIMENSION(5) :: A

    N = 5
    A = (/1, 2, 3, 4, 5/)
    SUM = 0

    ! LOOP TO CALCULATE THE SUM OF THE ARRAY
    DO I = 1, N
        SUM = SUM + A(I) ! ADD EACH ELEMENT TO SUM
    END DO

    PRINT *, 'SUM OF THE ARRAY IS:', SUM

END PROGRAM SUMARRAY
  

Python

Below is an example of Python:


import math
import sys

def calculate_area(radius):
    """
    Calculate the area of a circle.

    This function computes the area of a circle based on the provided radius.
    It uses the mathematical formula A = πr², where A is the area, π is Pi, and r is the radius.
    """
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return calculate_area(self.radius)

def main(args):
    if len(args) < 2:
        print("Usage: python script.py <radius>")
        sys.exit(1)

    radius = float(args[1])
    circle = Circle(radius)

    try:
        area = circle.area()
        print(f"Area of the circle: {area:.2f}")
    except ValueError as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main(sys.argv)
  

Matlab / Octave

Below is an example of Matlab / Octave:


function matlabExample
    % MATLAB Example Script

    % Calculate and display the factorial of 5
    n = 5;
    factN = factorial(n);
    fprintf('The factorial of %d is %d.\n', n, factN);

    % Check if a number is prime
    num = 29;
    if isprime(num)
        fprintf('%d is a prime number.\n', num);
    else
        fprintf('%d is not a prime number.\n', num);
    end

    % Generate and plot a sine wave
    f = 1; % frequency in Hz
    fs = 100; % sampling frequency in Hz
    t = 0:1/fs:1; % time vector from 0 to 1 second
    y = sin(2 * pi * f * t); % sine wave values

    figure; % create new figure window
    plot(t, y);
    title('Sine Wave');
    xlabel('Time (seconds)');
    ylabel('Amplitude');
    grid on;

    % Display a matrix and its transpose
    A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
    disp('Matrix A:');
    disp(A);

    AT = A'; % transpose of A
    disp('Transpose of A (A''):');
    disp(AT);

    % Use a for loop to display squares of the first 5 integers
    disp('Squares of the first 5 integers:');
    for i = 1:5
        disp(['Square of ', num2str(i), ' is ', num2str(i^2)]);
    end

    % Use a switch-case to display messages based on a variable's value
    switch n
        case 5
            disp('n is 5.');
        case 10
            disp('n is 10.');
        otherwise
            disp('n is neither 5 nor 10.');
    end
end

function fact = factorial(n)
    % Recursive function to calculate factorial
    if n == 0
        fact = 1;
    else
        fact = n * factorial(n-1);
    end
end

function isPrime = isprime(num)
    % Function to check if a number is prime
    isPrime = true;
    for i = 2:sqrt(num)
        if rem(num, i) == 0
            isPrime = false;
            break;
        end
    end
end
  

CMake

Below is an example CMakeList.txt:


cmake_minimum_required(VERSION 3.16)
project(MyProject VERSION 1.0)

# Environment variables / CMake variables
set(CMAKE_CXX_STANDARD 20)
set(SRC_FILES main.cpp utils.cpp)

# Add an executable
add_executable(${PROJECT_NAME} ${SRC_FILES})

# Compiler options
target_compile_definitions(${PROJECT_NAME} PRIVATE USE_CUSTOM_LOGGING)

# Additional directories
include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_SOURCE_DIR}/src)

# Link libraries
target_link_libraries(${PROJECT_NAME} PRIVATE MyLibrary)

# Use environment variables
if($ENV{BUILD_TYPE} STREQUAL "Debug")
  set(CMAKE_BUILD_TYPE Debug)
else()
  set(CMAKE_BUILD_TYPE Release)
endif()

# Add a library
add_library(MyLibrary STATIC lib.cpp)

# Output path for binaries
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

# Ensure compatibility with older CMake versions
if(CMAKE_VERSION VERSION_LESS 3.13)
  message(FATAL_ERROR "CMake version must be at least 3.13")
endif()

# Additional flags
list(APPEND CMAKE_CXX_FLAGS "-Wall -Wextra")

# Custom execute
execute_process(COMMAND echo "Building ${PROJECT_NAME} in ${CMAKE_BUILD_TYPE} mode")
  

Reverse Polish LISP (RPL)

Below is an example of RPL. Since most are commands, only the comment are highlighted:


* This System RPL program does as the command TYPE for real, complex, string, array, list and global types.
* For anything else it throws a "Bad Argument Type" error
::  CK1  :: CK&DISPATCH0
* real
      ONE       %0
* complex
      TWO       %1
* string
      THREE     %3
* array
      FOUR      %4
* list
      FIVE      %5
* global name
      SIX       %6
  ;
DUP
SWAPDROP ( Remove the original input )
"TYPE"
SWAP
;
  

Web & Markup Languages

HTML

The following stylesheet <link> need to be placed in the <head> and the <script> need to be placed near the end of the pages:


<!-- CSS Files -->
<link rel="stylesheet" href="/assets/css/syntax-highlights.min.css" />
<!-- JS Files -->
<script src="/assets/js/syntax-highlights.min.js" type="text/javascript"></script>

JavaScript

Below is an example of a JavaScript function:


function exampleFunc(arr) {
    let date = `${Date.now()}`;
    let result = '';
    var testHtml = `
          <div class="example" data-date="${date}">Toast Message</div>
        `;
    for (let i = 0; i < arr.length; i++) {
        switch (arr[i]) {
            case 'a':
                result += 'Alpha';
                break;
            case 'b':
                result += 'Beta';
                break;
            default:
                result += 'Unknown';
        }
        if (i < arr.length - 1) result += ', ';
    }
    document.getElementById('output').innerHTML += testHtml;
    return result;
}

CSS

Below is an example of CSS styling:


/* Sample CSS for testing syntax highlighting */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

body {
  background-color: #1B1D1E; /* Dark background */
  color: #F8F8F2; /* Light text */
  font-family: 'Arial', sans-serif;
}

a:hover {
  color: #F92672; /* Light pink for hover state */
  animation: fadeIn 0.3s ease-in-out;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  color: var(--hc-test);
}

.active-link {
  border-bottom: 2px solid #A6E22E; /* Lime green for active link underline */
}

/* Comment example */
/* Another comment line */
.footer {
  background-color: #66D9EF; /* Sky blue background for footer */
  color: #E6DB74; /* Yellow text color */
  padding: 10px;
  text-align: center;
}

JSON

Below is an example of JSON:


{
  "@context": "http://schema.org",
  "@type": "Article",
  "headline": "Your Article Title",
  "image": "https://example.com/photo.jpg",
  "author": {
    "@type": "Person",
    "name": "Author Name"
  },
  "datePublished": "2020-01-01",
  "publisher": {
    "@type": "Organization",
    "name": "Publisher Name",
    "logo": {
      "@type": "ImageObject",
      "url": "https://example.com/logo.jpg"
    }
  },
  "tags": ["Technology", "Innovation", "Science"],
  "viewCounts": [12345, 67890, 101112]
}
  

Embedded JavaScript

Below is an example of EJS:


<!DOCTYPE html>
<html>
<head>
    <title>EJS Example</title>
</head>
<body>
    <h1>EJS Data Rendering</h1>
    <% for(let i = 0; i < users.length; i++) { %>
        <div class="user">
            <h2><%= users[i].name %></h2>
            <p>Email: <%= users[i].email %></p>
            <p>Age: <%= users[i].age %></p>
            <% if(users[i].isAdmin) { %>
                <em>(Administrator)</em>
            <% } %>
        </div>
    <% } %>
</body>
</html>
  

Go to the top of the page