8

I was wondering how to generate permalinks from the following markup, using python markdown library:

A header
========

A paragraph

The desired output would be something like

<span id="a-header"></span>
<h1>
  A header
  <a class="headerlink" title="Permalink to this headline" href="#a-header">¶</a>
</h1>
<p>A paragraph</p>

Answer:

Thanks @BlaXpirit (see answer)

Use headerid python markdown extension and input the following:

# A header [¶](#a-header) {#a-header}

A paragraph

This generates the following output:

<h1 id="a-header">
  A header
  <a href="#a-header">¶</a>
</h1>

Then use some css styling to get the common output, something like :

h1 a{visibility:hidden;}
h1:hover a{visibility:visible;}
Community
  • 1
  • 1
aminho
  • 565
  • 6
  • 17

3 Answers3

1

Markdown in Python has an extension that does this.
It also lets you specify an id you like for the header, like this:

A header            {#a-header}
========
Oleh Prypin
  • 33,184
  • 10
  • 89
  • 99
1

You can generate permalinks with the Table of Contents extension for Python-Markdown. The Python-Markdown documentation notes that when possible it is preferable to pass an instance of an extension rather than a string.

import markdown
from markdown.extensions.toc import TocExtension

markup = """
A header
========

A paragraph
"""

html = markdown.markdown(markup, extensions=[TocExtension(permalink=True)])
print(html)


configs = {'toc': {'permalink': True}}
html = markdown.markdown(markup, extensions=['toc'], extension_configs=configs)
print(html)

An answer to a different question shows how you can change the paragraph symbol by setting the permalink option to a string.

Keegan Skeate
  • 21
  • 2
  • 6
  • thanks, although if you don't want these extra a tags, you can use `html = markdown.markdown(markup, extensions=[TocExtension(baselevel=1)])` – WyattBlue Aug 01 '21 at 23:53
0

Pandoc associates a unique identifier to each header based on the rule you imagined: the id is the downcase heading, spaces replace by hyphens. This is used to generate optional tables of contents for HTML and LaTeX and other output formats. In HTML it automatically makes linkable ids and in particular can be used for internal cross references; the markdown syntax is:

 See the section on [header identifiers](#header-identifiers-in-html).

as we read in the user's guide at http://johnmacfarlane.net/pandoc/README.html#header-identifiers-in-html

applicative
  • 8,081
  • 35
  • 38
  • Thanks, didn't know about Pandoc, but my question was about python markdown library – aminho Apr 13 '11 at 01:30
  • 1
    I wondered if this was the case, but it actually wasn't at all clear from the content of the question. I saw it on the markdown feed, I don't follow the python one. – applicative Apr 13 '11 at 21:06
  • you are right, i didn't explicitly mention python markdown library. I am going to update the question. – aminho Apr 13 '11 at 21:40