python-basic

⌘K
  1. Home
  2. Docs
  3. python-basic
  4. mkdocs
  5. Highlight.js

Highlight.js

Step 1: Install the Required Plugins

First, ensure you have the necessary MkDocs plugins installed. Run the following command to install mkdocs-material and pymdown-extensions:

pip install mkdocs-material pymdown-extensions
Bash

Step 2: Configure MkDocs to Use Highlight.js

Open your mkdocs.yml configuration file in your project directory. Add the following configuration to enable syntax highlighting with Highlight.js:

markdown_extensions:
  - pymdownx.highlight:
      linenums: true   # Enable line numbers if desired
      guess_lang: false   # Disable automatic language detection

extra_javascript:
  - https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/highlight.min.js

extra_css:
  - https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.4.0/styles/default.min.css
Bash

In this configuration:

  • pymdownx.highlight is enabled to handle syntax highlighting using Highlight.js.
  • linenums: true enables line numbers for code blocks (optional).
  • guess_lang: false disables automatic language detection, requiring you to specify the language for each code block.
  • extra_javascript and extra_css are used to include the Highlight.js library and its default stylesheet from a CDN (Content Delivery Network). Adjust the URLs if needed.

Step 3: Restart MkDocs Server

If your MkDocs server is running, stop it and restart it to apply the changes:

mkdocs serve
Bash

Step 4: Test Syntax Highlighting

Create or open a Markdown file containing code blocks in your docs directory. Use Markdown code fences (“`) to enclose your code blocks and specify the language

```python
def hello():
    print("Hello, World!")
Bash

How can we help?