Showdown - Documentation

Introduction

What is Showdown?

Showdown is a JavaScript Markdown to HTML converter. It’s a powerful and versatile library that allows you to easily integrate Markdown support into your web applications. It’s lightweight, fast, and supports a wide range of Markdown features, making it suitable for a variety of use cases, from simple blog posts to complex documentation websites. Showdown focuses on a clean and straightforward API, making it simple to integrate and use. It doesn’t rely on external dependencies, offering a self-contained solution for Markdown conversion.

Why use Showdown?

Setting up Showdown.

Showdown can be included in your project in several ways:

<script src="https://cdn.jsdelivr.net/npm/showdown@2.1.0/dist/showdown.min.js"></script>

Replace 2.1.0 with the desired version number.

npm install showdown

Then, you can import it into your JavaScript code:

import showdown from 'showdown';
// Or, if using CommonJS:
const showdown = require('showdown');

After including Showdown, you can create a converter instance and convert your Markdown text to HTML:

let converter = new showdown.Converter();
let html = converter.makeHtml('Your Markdown text here');
document.getElementById('output').innerHTML = html;

Remember to have an element with the id “output” in your HTML to display the converted HTML. Further customization options, such as configuring extensions, are detailed in the subsequent sections of this manual.

Basic Usage

Converting Markdown to HTML

The core functionality of Showdown revolves around converting Markdown text into HTML. This is accomplished using the Converter object and its makeHtml() method.

First, create a new converter instance:

let converter = new showdown.Converter();

Then, pass your Markdown text to the makeHtml() method:

let markdownText = "# This is a heading\n\nThis is a paragraph.";
let html = converter.makeHtml(markdownText);
console.log(html); // Outputs the corresponding HTML

The resulting html variable will contain the HTML representation of your Markdown input. You can then insert this HTML into your webpage using JavaScript’s DOM manipulation capabilities, for example, by setting the innerHTML property of an element:

document.getElementById('output').innerHTML = html;

Basic Markdown Syntax

Showdown supports a wide range of Markdown syntax. Generally, Markdown uses plain text formatting conventions to structure documents. Key aspects include using specific characters or symbols to denote headings, paragraphs, lists, emphasis, and other elements. Whitespace (spaces, tabs, newlines) is generally significant in structuring the content, but excessive whitespace is often ignored.

Headers

Headers are created using # symbols. The number of # symbols determines the header level (h1-h6):

# Heading 1
## Heading 2
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6

Paragraphs

Paragraphs are created by separating lines of text with one or more blank lines. Showdown automatically wraps sequences of non-blank lines into <p> tags.

This is a paragraph.

This is another paragraph.

Emphasis

Emphasis is achieved using asterisks (*) or underscores (_):

Lists

Unordered lists use asterisks (*), plus signs (+), or hyphens (-):

* Item 1
* Item 2
* Item 3

Ordered lists use numbers followed by a period (.) :

1. Item 1
2. Item 2
3. Item 3

Links are created using square brackets [] for the link text and parentheses () for the URL:

[Link text](https://www.example.com)

You can also specify a title attribute:

[Link text with title](https://www.example.com "Title text")

Images

Images are similar to links, but use an exclamation mark ! before the square brackets:

![Alt text](https://www.example.com/image.jpg)

You can also specify a title attribute:

![Alt text with title](https://www.example.com/image.jpg "Title text")

Advanced Usage

Code Blocks

Code blocks are created using triple backticks (```) or indented four spaces:

Triple backticks: This method allows for specifying a language for syntax highlighting (although Showdown itself doesn’t perform the highlighting; that would require a separate syntax highlighter library).

```javascript
function myFunction() {
  // Some JavaScript code
}

**Indented four spaces:**
This is a code block using indentation.

### Blockquotes

Blockquotes are created using the `>` character at the beginning of each line:

```markdown
> This is a blockquote.
> It can span multiple lines.

Horizontal Rules

Horizontal rules are created using three or more hyphens (---), asterisks (***), or underscores (___) on a line by themselves:

---
***
___

Tables

Tables are created using pipes (|) and hyphens (-):

| Header 1 | Header 2 | Header 3 |
|---|---|---|
| Row 1, Cell 1 | Row 1, Cell 2 | Row 1, Cell 3 |
| Row 2, Cell 1 | Row 2, Cell 2 | Row 2, Cell 3 |

You can optionally align columns by adding colons (:) to the hyphens in the header row:

HTML Entities

Showdown allows the inclusion of HTML entities directly in your Markdown:

&lt;p&gt;This is a paragraph using HTML entities.&lt;/p&gt;

Escaping Markdown Syntax

To include literal Markdown characters without them being interpreted, escape them using a backslash (\):

\*This is not italicized\*.

Footnotes

Showdown supports footnotes using the following syntax:

Here's a sentence with a footnote.<sup>[1]</sup>

[1]: This is the footnote.

Definitions

Showdown supports definition lists:

term 1
: definition 1

term 2
: definition 2

Extensions

Showdown’s functionality can be extended through the use of extensions. Extensions add support for features not included in the core Markdown specification, or modify the default behavior of the converter.

Enabling Extensions

Extensions are enabled when creating the Converter instance. You pass an array of extension names to the extensions option:

let converter = new showdown.Converter({ extensions: ['exampleExtension', 'anotherExtension'] });
let html = converter.makeHtml(markdownText);

Replace 'exampleExtension' and 'anotherExtension' with the actual names of the extensions you want to enable. Make sure the extension files are included in your project before using them. The exact method for including extensions will depend on how you’ve included Showdown (e.g., via CDN, npm, etc.).

Available Extensions

Showdown itself doesn’t include built-in extensions in the same way some Markdown processors do. The availability and functionality of extensions largely depend on community-contributed extensions or those you might create yourself. You’ll typically find information about available extensions on the Showdown project page or through community resources. There isn’t a central repository maintained by the Showdown project itself for extensions.

Custom Extensions

Showdown allows creating custom extensions to add new Markdown syntax or modify existing behavior. This typically involves creating a JavaScript object that conforms to Showdown’s extension API. The API details are documented separately (often within the Showdown project repository or documentation) and typically involve extending the parser or renderer to handle new syntax or modify the output. A custom extension would generally include methods to handle the new markdown element(s), such as:

Extension Options

Some extensions may offer configuration options. These options are passed as part of the extensions array using an object with the extension name as the key and an object containing the options as the value:

let converter = new showdown.Converter({
  extensions: [
    {
      type: 'output',
      name: 'myExtension',
      options: {
        myOption: 'myValue'
      }
    }
  ]
});

The specific options available depend entirely on the particular extension being used; consult the extension’s documentation for details. Note that the structure and required properties of the option object may differ based on how the extension is designed. The example above demonstrates one possible structure; you might need to adapt it based on the API defined by the extension.

Configuration

Showdown offers several ways to configure its behavior, allowing you to customize the Markdown parsing and HTML generation process.

Global Configuration

Global configuration affects all instances of the showdown.Converter created. This is generally done by setting properties directly on the showdown object before creating any converter instances. However, note that this approach isn’t officially supported or documented by the Showdown library, and its use might lead to unforeseen issues in larger projects or with future versions. It’s generally recommended to favor per-conversion configuration for better control and maintainability.

Per-Conversion Configuration

The preferred and recommended method of configuring Showdown is to pass options when creating a new showdown.Converter instance. This approach ensures that each converter instance has its own independent configuration, preventing conflicts and making your code more organized and easier to manage. Options are provided as a JavaScript object to the constructor.

let converter = new showdown.Converter({
    // Configuration options here
});

Configuration Options

Several configuration options are available, affecting various aspects of the conversion process. Some common options include:

The exact options available and their effects may vary across different Showdown versions. Consult the official Showdown documentation for the most up-to-date and comprehensive list of configuration options and their descriptions.

Default Options

Showdown has a set of default options that are used if you don’t specify any options when creating a converter. These defaults provide a reasonable balance of features and compatibility. To know the exact default values for a given Showdown version, check its documentation. Generally, the defaults tend to favor a reasonably broad range of Markdown features, providing good compatibility with many Markdown styles. However, if you have specific requirements or want to ensure consistency with a particular Markdown standard (such as GitHub Flavored Markdown), overriding the default options via the showdown.Converter constructor is the best approach.

API Reference

This section details the Showdown API, focusing on the core Converter object and its associated methods. Note that the specific methods and their behavior may vary slightly depending on the Showdown version. Always refer to the official Showdown documentation for the most up-to-date and comprehensive API reference.

Showdown.Converter

The showdown.Converter class is the primary object used for converting Markdown to HTML. It’s instantiated with optional configuration options (see the Configuration section). All conversion methods are called on a Converter instance. Creating a new instance is the first step in using Showdown:

const converter = new showdown.Converter({ /* options */ });

Converter.makeHtml

This is the core method for converting Markdown text to HTML. It takes the Markdown text as a string and returns the corresponding HTML as a string.

const markdown = "# My Heading\n\nThis is some text.";
const html = converter.makeHtml(markdown);
console.log(html); // Output: The generated HTML

Converter.setFlavor

Sets the Markdown flavor to be used. Common flavors include ‘github’ (GitHub Flavored Markdown) and ‘original’ (a more basic flavor). This method influences the parsing of certain Markdown syntax elements.

converter.setFlavor('github');

Converter.setOption

Sets an individual configuration option. This method allows modifying specific options without having to re-create the Converter instance.

converter.setOption('simplifiedAutoLink', true);

Converter.addExtension

Adds a new extension to the converter. This method allows extending the functionality of Showdown dynamically. The argument should be an object conforming to the Showdown extension API.

converter.addExtension(myCustomExtension);

Converter.removeExtension

Removes a previously added extension from the converter.

converter.removeExtension('myExtension');

Converter.getFlavor

Returns the currently set Markdown flavor.

const currentFlavor = converter.getFlavor();
console.log(currentFlavor); // Output: The current flavor (e.g., 'github')

Converter.getOptions

Returns all the currently set options for the converter as a single object. This allows introspection of the current configuration.

const options = converter.getOptions();
console.log(options); // Output: An object containing all options and their values.

Troubleshooting

This section provides guidance on resolving common issues encountered while using Showdown.

Common Errors

Debugging Tips

Troubleshooting Extensions

If you’re experiencing problems with extensions:

Community Support

If you can’t resolve the issue after trying the above steps, seek help from the Showdown community. You might find solutions in online forums, issue trackers, or by posting a question on a relevant programming Q&A site. Make sure to provide relevant information such as:

Remember to search existing resources before asking for help, as your problem may already have a known solution.

Contributing

This section outlines how to contribute to the Showdown project.

Contributing to Showdown

Contributions to Showdown are welcome and encouraged! Before contributing, please review the project’s contribution guidelines (typically found on the project’s GitHub repository). These guidelines will provide details on the preferred workflow, coding style, and testing procedures. Generally, contributions involve:

The contribution process typically involves forking the repository, creating a branch for your changes, making your modifications, testing thoroughly, and submitting a pull request. Clear commit messages and well-written code are crucial for a smooth and efficient review process.

Reporting Bugs

When reporting bugs, provide as much detail as possible to help developers reproduce and fix the issue quickly. This typically includes:

A well-written bug report significantly increases the chances of a swift resolution. Using a consistent bug reporting template (if one is provided by the project) helps ensure all necessary information is included.

Suggesting Features

When suggesting new features, provide a clear and detailed description of the proposed feature, including:

A well-articulated feature request helps the developers assess its feasibility and prioritize its implementation. Consider engaging in discussion with the maintainers to refine the proposal and ensure it aligns with the project’s goals.

Coding Style Guide

Adhere to the project’s coding style guide. This usually involves consistent formatting, naming conventions, and commenting practices. A well-formatted and consistently styled codebase is easier to read, understand, and maintain. The style guide will likely be found within the project’s repository or documentation; if not explicitly defined, follow widely accepted JavaScript style guides (such as the one from Airbnb or Google). Consistency and readability are paramount for collaborative coding.