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

500,201

Solution 1

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>

Solution 2

Github automatically parses anchor tags out of your headers. So you can do the following:

[Custom foo description](#foo)

# Foo

In the above case, the Foo header has generated an anchor tag with the name foo

Note: just one # for all heading sizes, no space between # and anchor name, anchor tag names must be lowercase, and delimited by dashes if multi-word.

[click on this link](#my-multi-word-header)

### My Multi Word Header

Update

Works out of the box with pandoc too.

Solution 3

This may be out-of-date thread but to create inner document links in markdown in Github use...
(NOTE: lowercase #title)

# Contents
 - [Specification](#specification) 
 - [Dependencies Title](#dependencies-title) 

## Specification
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

## Dependencies Title
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

A good question was made so I have edited my answer;

An inner link can be made to any title size using - #, ##, ###, #### I created a quick example below... https://github.com/aogilvie/markdownLinkTest

Solution 4

Experimenting, I found a solution using <div…/> but an obvious solution is to place your own anchor point in the page wherever you like, thus:

<a name="abcde">

before and

</a>

after the line you want to "link" to. Then a markdown link like:

[link text](#abcde)

anywhere in the document takes you there.

The <div…/> solution inserts a "dummy" division just to add the id property, and this is potentially disruptive to the page structure, but the <a name="abcde"/> solution ought to be quite innocuous.

(PS: It might be OK to put the anchor in the line you wish to link to, as follows:

## <a name="head1">Heading One</a>

but this depends on how Markdown treats this. I note, for example, the Stack Overflow answer formatter is happy with this!)

Solution 5

yes, markdown does do this but you need to specify the name anchor <a name='xyx'>.

a full example,

this creates the link
[tasks](#tasks)

elsewhere in the document, you create the named anchor (whatever it is called).

<a name="tasks">
   my tasks
</a>

note that you could also wrap it around the header too.

<a name="tasks">
### Agile tasks (created by developer)
</a>
Share:
500,201
recipriversexclusion
Author by

recipriversexclusion

Updated on April 14, 2022

Comments

  • recipriversexclusion
    recipriversexclusion about 2 years

    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.

    • Etienne Low-Décarie
      Etienne Low-Décarie about 10 years
      Link to stackoverflow.com/questions/12204257/… for R Markdown (Rmd).
    • userfuser
      userfuser over 8 years
      The only problem you had is that MyTitle should not be a title, but a name of an anchor in that document (like <a name="MyTitle"></a>). Then you'd be able to use your original linking, anywhere in the doc.
    • BrainSlugs83
      BrainSlugs83 almost 5 years
      The accepted answer is not actually relevant for most folks. Instead see the second answer down: stackoverflow.com/a/16426829/398630
  • recipriversexclusion
    recipriversexclusion almost 14 years
    Uh oh! Do you know if MultiMarkdown or Textile support it? I was thinking of migrating to MD for all my documentation but this a deal breaker. Thanks for the help!
  • recipriversexclusion
    recipriversexclusion almost 14 years
    Thanks, this was exactly what I needed. I was using Textmate to convert Markdown to HTML, will switch to pandoc.
  • applicative
    applicative almost 14 years
    You might give the demo Pandoc tmbundle up on Github a try (there's also emacs pandoc-mode, etc.) The tmbundle re-uses the MultiMarkdown-specific syntax highlighter, so there are a (very) few oddities. Also, a lot of the associated scripts are highly customized -- e.g. Context, not LaTeX etc. -- but the idea is that the users will alter them as they please, which I found pretty simple. It should probably be git clone -ed into the lowest or outermost tmbundle directory, ~/Library/Application\ Support/TextMate/Bundles to simplify integration.
  • Steve Powell
    Steve Powell almost 13 years
    I wonder what pandoc does in the case of two headings with the same name?
  • applicative
    applicative almost 13 years
    It adds -1 to the first repetition of the id, -2 to the second, etc.
  • 2rs2ts
    2rs2ts almost 13 years
    While the software reference was appreciated, I found that I can't get this to work for markdown-to-markdown, even though adding the HTML would be perfectly valid for markdown. I also can't get it to work for markdown-to-html or html-to-html without the CSS being stripped. (Other immediate complaints about the tool aside.) Cool, but frustrating.
  • 2rs2ts
    2rs2ts almost 13 years
    If you do this you should be aware that the div strips other markdown formatting, such as ## headers.
  • Steve Powell
    Steve Powell almost 13 years
    @user691859 Can you elaborate? Perhaps we can update an answer to make it work better. I saw TextMate suppress highlighting, until I indented the div, but no problem with the processed markdown viewed from a browser.
  • 2rs2ts
    2rs2ts almost 13 years
    In WriteMonkey I found that if I precede any text with the <div/> several lines below are affected. Instead I have to wrap the text I am linking in a full div tag clause and I have to RE-SPECIFY the behavior from scratch using real HTML. Boo.
  • Steve Powell
    Steve Powell almost 13 years
    I overlooked the most obvious tag to put in, and this also works for me. Put in a named anchor tag! Update to main answer follows.
  • Alex Dean
    Alex Dean about 12 years
    This works well, thanks. For anyone wondering, this also works with GitHub-hosted-and-displayed Markdown files.
  • Duncan Lock
    Duncan Lock almost 12 years
    I found that I had to add the --standalone option to the pandoc command to get it to actually output the table of contents itself in the output. Without that switch, it would make the headers into links back to the #toc named anchor, but not actually output the named anchor and list of like itself.
  • binki
    binki over 10 years
    To be forward-compatible with HTML5, I would like to recommend replacing <a name="head1"/> with <a id="head1"/>.
  • Steve Powell
    Steve Powell over 10 years
    @binki To understand why I do not recommend id= see the answer here.
  • binki
    binki over 10 years
    @StevePowell If I am reading HTML5 §5.2.4 right and your concern is that setting id attribute adds new named properties to the Window/JavaScript global object, I think <a name="head1"/> will have the same issues as <a id="head"/> (even though the browsers I tested seem not to have implemented that yet).
  • Karim Bahgat
    Karim Bahgat about 10 years
    In your example, the link tags only have one #, but the headers that they are supposed to link to have two ##; shouldn't they be the same?
  • Ally
    Ally about 10 years
    Good question. The answer is no. the # in (#dependencies-title) tells Github markdown this is an inner link. The text that follows can be any title size. Here is an example test I made...https://github.com/aogilvie/markdownLinkTest
  • meteorainer
    meteorainer about 10 years
    Does that depend on the flavor of markdown? It seems like it works fine in the markdown editor, but when I save to html or pdf the ids dont get added to the appropriate tags. I'd be fine just dumping an anchor in there, but it seems like your method is so much cleaner and faster.
  • kon psych
    kon psych about 9 years
    Notice that this might not work as expected with all export tools or renderers. I had to use ## <a name="head1">Heading One<\a>
  • Benjohn
    Benjohn over 8 years
    Review of some OS X Apps: "Markdown Pro" supports this syntax. "Byword" 2.3 (2772) and "iA Writer" 2.1.3 (5984) show the link in rendered output but are not able to resolve it.
  • Zen
    Zen over 8 years
    A tip, when using macdown software on OSX, you should use <a name=" "> keyword </a> form to avoid display issues.
  • Zelphir Kaltstahl
    Zelphir Kaltstahl over 8 years
    What do you mean by "directive"? Other solutions to exactly the problem have been posted here.
  • Mogsdad
    Mogsdad about 8 years
    If your header contains multiple words, "Like this one", replace spaces with hyphens in the anchor [just](#like-this-one).
  • CarlosRos
    CarlosRos about 8 years
    In ST3 with the "Markdown Preview" package, all the anchor tags are prepended with user-content-, which is a shame...
  • Kevin Zakka
    Kevin Zakka almost 8 years
    What if the title contains a ? or !
  • GrayedFox
    GrayedFox over 7 years
    Does this only work for H1 headers? If linking to a H2 header (i.e. ## Foo), do I also need to put two number signs in the link, i.e. [Foo](##foo)? I cannot get your syntax or mine to work (with the extra number sign).
  • Abdull
    Abdull over 7 years
    @GrayedFox, if you want to create a link for ab H2 header ## Foo, try [this is my link to Foo](#foo) ... that is: single hash, no space between hash and lowercase-kebab-case-name-of-header
  • Alexander Pacha
    Alexander Pacha almost 7 years
    As a tip: check out the anchor that is displayed next to your header on Github to obtain the respective link, i.e. if it contains special characters, they are automatically removed and the correct link is shown there.
  • Aditya
    Aditya over 6 years
    What about when the headings have number ? # 3. Third point [Third point](#3.-third.point) doesn't work
  • Waldir Leoncio
    Waldir Leoncio about 6 years
    @Aditya, try ignoring the period in your cross-reference. That's what happens with the plus sign, for instance. So a section called # C++ would be referenced as [ref](#c).
  • WesternGun
    WesternGun almost 6 years
    It works well for StackEdit with id, name not. I just add an empty <div id="xxx"></div> before the title to link to not break the structure.
  • Anders Rabo Thorbeck
    Anders Rabo Thorbeck over 4 years
    The question makes no mention of GitHub, so I don't understand why this most upvoted answer is GitHub specific. This approach does not seem to work with other markdown parsers, such as MacDown.
  • Justin K
    Justin K over 4 years
    I came here looking for a GitHub-specific answer so while this isn't the most general answer, it helped me.
  • musicformellons
    musicformellons about 4 years
    Uh..., seemed nice. Tried it, two problems: (1). ## Chapter 1 needs an open line above it. (2). The link does not work...
  • musicformellons
    musicformellons about 4 years
    Ah, it doesn't work in intellij markdown plugin I used; but DOES work in Macdown markup editor.
  • musicformellons
    musicformellons about 4 years
    Still, tested on github: open line above the header is required, but it works.
  • ePi272314
    ePi272314 about 4 years
    @musicformellons can you please try without the opening line but properly closing the span tag?<br> <span id="Chapter1"><span>
  • Johan Maes
    Johan Maes almost 4 years
    @recipriversexclusion I think this should be the accepted answer.
  • dadhi
    dadhi almost 4 years
    For me in GitHub works only the approach with the empty line between <div... and the section ##
  • Pegasis
    Pegasis almost 4 years
    If you have more than one headers with the same name, you can use [first header](#header), [second header](#header-1) and [third header](#header-2)
  • Luís de Sousa
    Luís de Sousa over 3 years
    Works on GitLab too.
  • Danilo Matrangolo Marano
    Danilo Matrangolo Marano over 3 years
    If there is some different character like ., ? or `` you can just omit. Don't work on atom but works on GitHub.
  • Henke
    Henke over 3 years
    This answer is true only after you have exported the md to some other format, like PDF or HTML. As long as you remain in md it does not work. See stackoverflow.com/a/2822864.
  • Steve Powell
    Steve Powell over 3 years
    The markdown spec explicitly allows html tags, so this is allowed. And it works. At least last time I tried it.
  • Steve Powell
    Steve Powell over 3 years
    @Henke I think the anchor tag is allowed in markdown documents, (daringfireball.net/projects/markdown/syntax#html in the section Inline Html) and this question explicitly asks about linking within the same document so your decomposition is not a solution.
  • Jepolo
    Jepolo over 3 years
    Works like this in Typora too.
  • jhovanec
    jhovanec over 3 years
    For anyone looking for how to do this on Bitbucket I needed to add an anchor tag like in the following: # Foo <a name="foo"></a> and then reference it as: [Custom foo description](#foo)
  • steinybot
    steinybot about 3 years
    <a id="MyTitle"></a> is the only thing that also seems to work in IntelliJ's Markdown plugin.
  • Steve Powell
    Steve Powell about 3 years
    This may be correct in Github’s markdown implementation but it is not supported in plain markdown (as defined by the specification daringfireball.net/projects/markdown/syntax#html). In that spec there is no anchor created automatically by a header so the explicit anchor is the only guaranteed solution that will work everywhere.
  • HenriDev
    HenriDev about 3 years
    for those using Typora use ctrl+click to make the jump to the reference
  • galian
    galian almost 3 years
    In Boostnote, it's case sensitive. - [Specification](#Specification) - [Dependencies Title](#Dependencies-Title)
  • rturquier
    rturquier almost 3 years
    Replacing spaces with dashes doesn't seem to work in Typora and Obsidian. What does work is wrapping the section name in < and >: [link to header](<#Multiple word header>) This also seem to work with special characters.
  • KansaiRobot
    KansaiRobot over 2 years
    adding <a> adds a link.
  • KansaiRobot
    KansaiRobot over 2 years
    I tried it. It doesn't work. <a> creates a link to nowhere
  • Steve Powell
    Steve Powell over 2 years
    To @KansaiRobot : Adding an anchor element <a> adds an anchor which can be the target of a link; it does not add a link.
  • Steve Powell
    Steve Powell over 2 years
    @KansaiRobot It doesn't create a link; it creates an anchor which can be the target of a link. You have to write a link to get to it. Also you have to name the anchor so you can refer to it by name in the link.
  • Steve Powell
    Steve Powell over 2 years
    This is true for Multimarkdown; the explicit anchor method <a> should work in any Markdown document. Furthermore you can put an anchor anywhere in the document body, not just in headings, images or tables.
  • magic_al
    magic_al over 2 years
    The file is anticipated automatically, you don't need to specify it. [series expansion formula of the Boettcher function](#series-expansion-formula-of-the-boettcher-functio‌​n) should do the trick.
  • dimitrieh
    dimitrieh over 2 years
    For google: This also works in Storybook JS docs or documentation pages
  • Rogelio Prieto
    Rogelio Prieto over 2 years
    I share you a awk script to automatically generate links (in this example for second level: ##). bash awk '$0 ~ /^## / {gsub(/^## /,"",$0); gsub(/ $/,"",$0); mytitle=$0; $0=tolower($0); gsub(/\(/,"",$0); gsub(/\)/,"",$0); gsub(/ /,"-",$0); print "["mytitle"]""(#"$0")" }'
  • Minsky
    Minsky about 2 years
    Dang I was missing lowercasing. Thank you for that tip.
  • Ruslan
    Ruslan almost 2 years
    <a name="MyTitle">My Title</a> works well with Doxygen, which doesn't create any anchors by itself.
  • hc_dev
    hc_dev almost 2 years
    It's just a shallow duplicate of already answered. What is the difference?