Search code examples
markdownmultimarkdown

How to link to part of the same document in Markdown?


I am writing a large Markdown document and would like to place a table of contents of sorts at the beginning that will provide links to various locations in the document. How can I do this?

I tried using:

[a link](# MyTitle)

where MyTitle is a title within the document but this didn't work.


Solution

  • In pandoc, if you use the option --toc in producing html, a table of contents will be produced with links to the sections, and back to the table of contents from the section headings. It is similar with the other formats pandoc writes, like LaTeX, rtf, rst, etc. So with the command

    pandoc --toc happiness.txt -o happiness.html
    

    this bit of markdown:

    % True Happiness
    
    Introduction
    ------------
    
    Many have posed the question of true happiness.  In this blog post we propose to
    solve it.
    
    First Attempts
    --------------
    
    The earliest attempts at attaining true happiness of course aimed at pleasure. 
    Soon, though, the downside of pleasure was revealed.
    

    will yield this as the body of the html:

    <h1 class="title">
        True Happiness
    </h1>
    <div id="TOC">
        <ul>
            <li>
                <a href="#introduction">Introduction</a>
            </li>
            <li>
                <a href="#first-attempts">First Attempts</a>
            </li>
        </ul>
    </div>
    <div id="introduction">
        <h2>
            <a href="#TOC">Introduction</a>
        </h2>
        <p>
            Many have posed the question of true happiness. In this blog post we propose to solve it.
        </p>
    </div>
    <div id="first-attempts">
        <h2>
            <a href="#TOC">First Attempts</a>
        </h2>
        <p>
            The earliest attempts at attaining true happiness of course aimed at pleasure. Soon, though, the downside of pleasure was revealed.
        </p>
    </div>