Automatic TOC in github-flavoured-markdown - github

Is it possible to generate an automatic Table of Contents using Github Flavoured Markdown?

I created two options to generate a toc for github-flavored-markdown:
DocToc Command Line Tool (source) requires node.js
Installation:
npm install -g doctoc
Usage:
doctoc . to add table of contents to all markdown files in the current and all sub directories.
DocToc WebApp
If you want to try it online first, go to the doctoc site,
paste the link of the markdown page and it will generate a table of
content that you can insert at the top of your markdown file.
Github Wikis and Anchors
As Matthew Flaschen pointed out in the comments below, for its wiki pages GitHub previously didn't generate the anchors that doctoc depends on.
UPDATE: However, they fixed this issue.

GitHub Pages (which is basically a wrapper for Jekyll) appears to use kramdown, which implements all of Maruku, and therefore has support for an automatically generated table of contents via atoc attribute:
* auto-gen TOC:
{:toc}
The first line just starts an unordered list and is actually thrown away.
This results in a nested set of unordered lists, using the headers in the document.
Note: this should work for GitHub Pages, not GitHub Flavored Markdown (GFM) as used in comments or wiki pages. AFAIK a solution doesn't exist for that.

If you edit Markdown files with Vim, you can try this plugin vim-markdown-toc.
The usage is simple, just move your cursor to the place you want to append Table of Contents and run :GenTocGFM, done!
Screenshots:
Features:
Generate toc for Markdown files. (Support GitHub Flavored Markdown and Redcarpet)
Update existing toc.
Auto update toc on save.

Update March 2021: GitHub added an official workaround
READMEs now show a ToC like this as you scroll down into them:
demo: https://github.com/cirosantilli/test-git-web-interface/tree/master/d
It does not render inside the document as I wanted for better Ctrl + F, but it is better than nothing.
Also also works for non-README as well now, e.g.: https://github.com/cirosantilli/test-git-web-interface/blob/master/md.md
They also added a repository setting to enable disable that. It's so weird, who would ever want to disable it? Under https://github.com/cirosantilli/test-git-web-interface/settings Features:
Table of contents
Autogenerate table of contents for Markdown files in this repository. The table of contents will be displayed near the top of the file.
Original answer
It's not possible, except for the workarounds proposed.
I proposed Kramdown TOC extension and other possibilities to support#github.com and Steven! Ragnarök replied with the usual:
Thanks for the suggestion and links. I'll add it to our internal feature request list for the team to see.
Let's upvote this question until it happens.
Another workaround is to use Asciidoc instead of Markdown, which does render TOCs. I've moved to this approach for my content nowadays.

It's not automatic, but it uses Notepad++ regular expressions:
Replace all first by the second (removes all lines not having headers)
^##(#?)(#?)(.*?)$(.|\r|\n)*?(?=^##|\z)
-\1\2 [\3](#\3)\n
Then (converts headers III to spaces)
-##
-
Then (converts headers II to spaces)
-#
-
Then (remove unused chars at the beginning and at the end of link title)
\[ *((?:(?![ .:#!\?;]*\])[^#])*)[ #:!\?;]*\]
[\1]
Then (convert last tokens lowercase and dash instead of spaces)
\]([^ \r\n]*) ([^\r\n ]*)
]\L\1-\2
Remove unused final pounds and initial dashes:
(?:()[-:;!\?#]+$|(\]#)-)
\1\2
Remove useless chars in links:
(\].*?)(?:\(|\))
\1
And finally add parenthesis around final links:
\](?!\()(.*?)$
\]\(\1\)
And voilà! You can even put this in a global macro if you repeat it enough time.

Github Flavored Markdown uses RedCarpet as their Markdown engine.
From the RedCarpet repo:
:with_toc_data - add HTML anchors to each header in the output HTML,
to allow linking to each section.
It seems in that you'd need to get at the renderer level to set this flag, which isn't possible on Github obviously. However, the latest update to Github Pages, it seems that automatic anchoring is turned on for headers, creating linkable headings. Not exactly what you want, but it might help you create a TOC for your doc a bit easier (albeit manually).

A very convenient way to achieve a table of contents for a mardown file when working with Visual Studio Code is the extension Markdown-TOC.
It can add a toc to existing markdown files and even keep the toc up-to-date on saving.

It is possible to generate a webpage automatically with http://documentup.com/ from the README.md file. It's not creating a TOC, but for many it might solve the reason for wanting to create a TOC.
Another alternative to Documentup is Flatdoc: http://ricostacruz.com/flatdoc/

Gitdown is a markdown preprocessor for Github.
Using Gitdown you can:
Generate Table of Contents
Find dead URLs and Fragment Identifiers
Include variables
Include files
Get file size
Generate Badges
Print Date
Print information about the repository itself
Gitdown streamlines common tasks associated with maintaining a documentation page for a GitHub repository.
Using it is straightforward:
var Gitdown = require('gitdown');
Gitdown
// Gitdown flavored markdown.
.read('.gitdown/README.md')
// GitHub compatible markdown.
.write('README.md');
You can either have it as a separate script or have it as part of the build script routine (such as Gulp).

Use coryfklein/doctoc, a fork of thlorenz/doctoc that does not add "generated with DocToc" to every table of contents.
npm install -g coryfklein/doctoc

Majority of other answers require to install some tool.
I found a quick and easy online solution https://imthenachoman.github.io/nGitHubTOC.
For any markdown input it generates table of content output.
You can specify minimum and maximum heading level.
The source code is located at https://github.com/imthenachoman/nGitHubTOC

My colleague #schmiedc and I have created a GreaseMonkey script that installs a new TOC button left of the h1 button which uses the excellent markdown-js library to add/refresh a table of contents.
The advantage over solutions like doctoc is that it integrates into GitHub's wiki editor and does not need users to work on their command-line (and require users to install tools like node.js). In Chrome, it works by drag 'n dropping into the Extensions page, in Firefox you will need to install the GreaseMonkey extension.
It will work with plain markdown (i.e. it does not handle code blocks correctly, as that is a GitHub extension to markdown). Contributions welcome.

This is a not a direct answer to this question as so many people have provided workarounds. I don't think generating a TOC has been officially supported by Github yet to-date. If you want GitHub to render a Table of Contents on their GFM preview pages automatically, please participate the discussion on the official feature request issue.

Shameless "borrow" of this SO answer.
You can do this with Pandoc.
pandoc -s --toc input.md -o input_toc.md
Note: the order of the input and output files is important here.

Currently it's not possible using markdown syntax (see the ongoing discussion at GitHub), however you can use some external tools such as:
Online Table Of Content Generator (raychenon/play-table-of-contents)
arthurhammer/github-toc - browser extension that adds a table of contents to GitHub repos
Alternatively use AsciiDoc instead (e.g. README.adoc), e.g.
:toc: macro
:toc-title:
:toclevels: 99
# Title
## A
### A2
## B
### B2
as suggested in this comment. Check the demo here.

For Github's Texteditor Atom check out this awesome plugin (or "package" in Atom-lingo), which generates "TOC (table of contents) of headlines from parsed markdown" files:
markdown-toc
Once installed as Atom-package you can use the shortcut ctrl-alt-c to insert a TOC based on your markdown-doc-structure at the current cursor position...
Screenshots:
Atom Keybindings
markdown-toc gives you the following default key-bindings to control the plugin in Atom:
ctrl-alt-c => create TOC at cursor position
ctrl-alt-u => update TOC
ctrl-alt-r => delete TOC
Plugin Features (from the project's README)
Auto linking via anchor tags, e.g. # A 1 → #a-1
Depth control [1-6] with depthFrom:1 and depthTo:6
Enable or disable links with withLinks:1
Refresh list on save with updateOnSave:1
Use ordered list (1. ..., 2. ...) with orderedList:0

Here's a shell script I threw together today for this. Might need to tweak it for your needs, but it should be a good starting point.
cat README.md \
| sed -e '/```/ r pf' -e '/```/,/```/d' \
| grep "^#" \
| tail -n +2 \
| tr -d '`' \
| sed 's/# \([a-zA-Z0-9`. -]\+\)/- [\1](#\L\1)/' \
| awk -F'(' '{for(i=2;i<=NF;i++)if(i==2)gsub(" ","-",$i);}1' OFS='(' \
| sed 's/^####/ /' \
| sed 's/^###/ /' \
| sed 's/^##/ /' \
| sed 's/^#//'
If anyone knows a better way to do those final # replacements, please add a comment. I tried various things and wasn't happy with any, so I just brute forced it.

There's now a GitHub Action accomplishing this:
https://github.com/marketplace/actions/toc-generator
Specify location of TOC (option)
e.g. README.md
<!-- START doctoc -->
<!-- END doctoc -->
Setup workflow
e.g. .github/workflows/toc.yml
on: push
name: TOC Generator
jobs:
generateTOC:
name: TOC Generator
runs-on: ubuntu-latest
steps:
- uses: technote-space/toc-generator#v2

Update 2022-02
In VSCode, check out extension "Markdown All in One". It will generate and update the TOC of markdown automatically.
Install Extension.
Place cursor at where you want to insert TOC.
Run command "Markdown All in One: Create Table of Contents"
Enjoy!

Related

markdown github - how to do green code added git and red code deleted in README?

how to do this, coloring lines (like git)?
here is an example where it is used: https://github.com/sveltejs/kit/discussions/7716
in markdown, in GitHub readme.
TLDR
add the symbol + and - (with diff syntax in markdown)
symbol
+
-
name
Addition
Deletion
color
Green
Red
what it does do?
code that being added or changed code
code that being deleted or removed
how to write it in MD?
```diff
-oldText
+newText
```
how it will look?
real example to copy and paste.
see here, I created a gist for you: https://gist.github.com/Laaouatni/1f0825dc0c531eb7cfb49ecc9560094c (click raw to copy code)
now you will be asking me,
why diff in particular?
by just going to google and searching: https://www.google.com/search?q=what+diff+means+linux
the first thing that came to my mind is the command diff, and I tried to search if diff is actually used in markdown, and it turns out that the info is true so it was real.
so use diff instead of javascript/python, or whatever...
https://gist.github.com/Laaouatni/1f0825dc0c531eb7cfb49ecc9560094c (click raw to copy code)
do I manually need to add the symbols?
I always suggest little lines... so it will be easier for you to manually add the symbols.
but if you have a lot of lines,
then you don't have to manually add + and -,
since if you have Linux just use the diff command, and will return you the text that you can copy and paste to GitHub.
by searching for differences in 2 files.
the command is something like this:
diff example1.txt example2.txt
if you are on windows, I am not pretty sure it will work or not, but try to see it here: What is the Windows equivalent of the diff command?, but yeah if it is only for 2 or maximum 10 lines I think writing manually can be time-saving... but you have entire pieces of code then do your research if you think it will worth the time.
attention:
by using a diff language name, now you can have this special design.
also, this works only in GitHub,
and you can't color highlight for a specified language like python or javascript for example...
example: there isn't any color highlighting
so use it when necessary to point out a breaking change for example.

asciidoc: is there a way to create an anchor that will be visible in libreoffice writer?

Tl;dr;
What is the correct way to create an anchor in docbook? and is there a way that will make the anchor visible in writer?
Background
I am trying to split up documentation that was previously in single open office documents into smaller asciidoc documents which are both included in the main open office document and also converted to either or both of html & pdf.
I have this mostly working. I use asciidoctor to create html. asciidoctor-pdf to create pdf and a combination of asciidoctor and pandoc to create .odt files. I also tried the python implementation of asciidoc but found the interface less useable.
Round tripping between asciidoc and odt is obviously not possible. This is sort of a fusion where the master document is word processed but pieces of content that can be produced independently (think man pages - in fact that is one of several use cases) are included.
asciidoc to html:
asciidoctor -b html5 foo.adoc -o foo.html
asciidoc to pdf:
asciidoctor-pdf -b pdf foo.adoc -o foo.pdf
asciidoc to odt
asciidoctor -b docbook foo.adoc -o foo.docbook
pandoc --base-header-level=3 -V date:"" -V title:"" -f docbook foo.docbook -o foo.odt
With pandoc I have to nullify the date and title and set the header-level as desired for the section to be inserted as an extra complication.
I insert the resulting .odt into the main document using insert section inside open office.
Note that the main document is not a master document as I could not find a way of creating a master document without also automatically splitting the file on h1 boundaries.
I have two main problems to resolve with this set-up. I would like to add headings in the asciidoc document as cross references and also create entries for them in the alphabetical index (actually the first heading would be suffcient). Is there a way to do this?
Index markers in asciidoc do not result in entries in .odt file being created.
I am able to cross reference content in the inserted section using "insert reference/heading" and referencing the uniquely named header. However, whenever I use "update all" these cross references are invalidated. They are shown as "Error: Reference source not found".
[On a separate note I would also like a way to find broken cross references automatically]
I am currently using libreoffice - Version: 4.3.7.2
I am not adverse to switching version or flavours (i.e. apache) if one behaves better than the other.
I'm not sure if the answer is in the asciidoc or docbook parts of the chain. I would accept an answer which inserts a index entry at the start of the inserted section (top of the .adoc/docbook file) automatically.
I am also open to changing my toolchain to something that will work.
For example I tried the asciidoc-odt backend and fell foul of https://github.com/dagwieers/asciidoc-odf/issues/47 which does not inspire confidence.
Using asciidoc-odt I avoid the need to create an intermediate docbook file. However, I still can't get the anchor to appear.
I can get a macro to create an anchor but at present I haven't figured out how to run the macro from the command line.
To create an anchor in DocBook, make an inline anchor in the .adoc file. For example, giving this to asciidoctor:
[[X1]]Section1
---------------
produced this:
<title>
<anchor xml:id="X1" xreflabel="[X1]"/>
Section1
</title>
Conversely, putting this on separate lines did not create an anchor tag in my test:
[[X1]]
Section 1
Now for some bad news. From the Pandoc User's Guide:
Internal links are currently supported for HTML formats (including HTML slide shows and EPUB), LaTeX, and ConTeXt.
I interpret this to mean that currently, Pandoc does not create internal links in Writer. When I tried it, the link was ignored.
Note: It looks like I did not answer all of your questions. If you want to ask more about LibreOffice cross references and headings (the big bold paragraph towards the end of the question), maybe you could make a separate question just for that part.

Latex rendering in README.md on Github

Is there any way to render LaTex in README.md in a GitHub repository? I've googled it and searched on stack overflow but none of the related answers seems feasible.
For short expresions and not so fancy math you could use the inline HTML to get your latex rendered math on codecogs and then embed the resulting image. Here an example:
- <img src="https://latex.codecogs.com/gif.latex?O_t=\text { Onset event at time bin } t " />
- <img src="https://latex.codecogs.com/gif.latex?s=\text { sensor reading } " />
- <img src="https://latex.codecogs.com/gif.latex?P(s | O_t )=\text { Probability of a sensor reading value when sleep onset is observed at a time bin } t " />
Which should result in something like the next
Update: This works great in eclipse but not in github unfortunately. The only work around is the next:
Take your latex equation and go to http://www.codecogs.com/latex/eqneditor.php, at the bottom of the area where your equation appears displayed there is a tiny dropdown menu, pick URL encoded and then paste that in your github markdown in the next way:
![equation](http://latex.codecogs.com/gif.latex?O_t%3D%5Ctext%20%7B%20Onset%20event%20at%20time%20bin%20%7D%20t)
![equation](http://latex.codecogs.com/gif.latex?s%3D%5Ctext%20%7B%20sensor%20reading%20%7D)
![equation](http://latex.codecogs.com/gif.latex?P%28s%20%7C%20O_t%20%29%3D%5Ctext%20%7B%20Probability%20of%20a%20sensor%20reading%20value%20when%20sleep%20onset%20is%20observed%20at%20a%20time%20bin%20%7D%20t)
I upload repositories with equations to Gitlab because it has native support for LaTeX in .md files:
```math
SE = \frac{\sigma}{\sqrt{n}}
```
The syntax for inline latex is $`\sqrt{2}`$.
Gitlab renders equations with JavaScript in the browser instead of showing images, which improves the quality of equations.
More info here.
Let's hope Github will implement this as well in the future.
My trick is to use the Jupyter Notebook.
GitHub has built-in support for rendering .ipynb files. You can write inline and display LaTeX code in the notebook and GitHub will render it for you.
Here's a sample notebook file: https://gist.github.com/cyhsutw/d5983d166fb70ff651f027b2aa56ee4e
Readme2Tex
I've been working on a script that automates most of the cruft out of getting LaTeX typeset nicely into Github-flavored markdown: https://github.com/leegao/readme2tex
There are a few challenges with rendering LaTeX for Github. First, Github-flavored markdown strips most tags and most attributes. This means no Javascript based libraries (like Mathjax) nor any CSS styling.
The natural solution then seems to be to embed images of precompiled equations. However, you'll soon realize that LaTeX does more than just turning dollar-sign enclosed formulas into images.
Simply embedding images from online compilers gives this really unnatural look to your document. In fact, I would argue that it's even more readable in your everyday x^2 mathematical slang than jumpy .
I believe that making sure that your documents are typeset in a natural and readable way is important. This is why I wrote a script that, beyond compiling formulas into images, also ensures that the resulting image is properly fitted and aligned to the rest of the text.
For example, here is an excerpt from a .md file regarding some enumerative properties of regular expressions typeset using readme2tex:
As you might expect, the set of equations at the top is specified by just starting the corresponding align* environment
**Theorem**: The translation $[\![e]\!]$ given by
\begin{align*}
...
\end{align*}
...
Notice that while inline equations ($...$) run with the text, display equations (those that are delimited by \begin{ENV}...\end{ENV} or $$...$$) are centered. This makes it easy for people who are already accustomed to LaTeX to keep being productive.
If this sounds like something that could help, make sure to check it out. https://github.com/leegao/readme2tex
Since May 2022, this has been officially supported:
Inline:
Where $x = 0$, evaluate $x + 1$
Blocks:
Where
$$x = 0$$
Evaluate
$$x + 1$$
One can also use this online editor: https://www.codecogs.com/latex/eqneditor.php which generates SVG files on the fly. You can put a link in your document like this:
![](https://latex.codecogs.com/svg.latex?y%3Dx%5E2) which results in:
.
I test some solution proposed by others and I would like to recommend TeXify created and proposed in comment by agurodriguez and further described by Tom Hale - I would like develop his answer and give some reason why this is very good solution:
TeXify is wrapper of Readme2Tex (mention in Lee answer). To use Readme2Tex you must install a lot of software in your local machine (python, latex, ...) - but TeXify is github plugin so you don't need to install anything in your local machine - you only need to online installation that plugin in you github account by pressing one button and choose repositories for which TeXify will have read/write access to parse your tex formulas and generate pictures.
When in your repository you create or update *.tex.md file, the TeXify will detect changes and generate *.md file where latex formulas will be exchanged by its pictures saved in tex directory in your repo. So if you create README.tex.md file then TeXify will generate README.md with pictures instead tex formulas. So parsing tex formulas and generate documentation is done automagically on each commit&push :)
Because all your formulas are changed into pictures in tex directory and README.md file use links to that pictures, you can even uninstall TeXify and all your old documentation will still works :). The tex directory and *.tex.md files will stay on repository so you have access to your original latex formulas and pictures (you can also safely store in tex directory your other documentation pictures "made by hand" - TeXify will not touch them).
You can use equations latex syntax directly in README.tex.md file (without loosing .md markdown syntax) which is very handy. Julii in his answer proposed to use special links (with formulas) to external service e.g . http://latex.codecogs.com/gif.latex?s%3D%5Ctext%20%7B%20sensor%20reading%20%7D which is good however has some drawbacks: the formulas in links are not easy (handy) to read and update, and if there will be some problem with that third-party service your old documentation will stop work... In TeXify your old documentation will works always even if you uninstall that plugin (because all your pictures generated from latex formulas are stay in repo in tex directory).
The Yuchao Jiang in his answer, proposed to use Jupyter Notebook which is also nice however have som drawbacks: you cannot use formulas directly in README.md file, you need to make link there to other file *.ipynb in your repo which contains latex (MathJax) formulas. The file *.ipynb format is JSON which is not handy to maintain (e.g. Gist don't show detailed error with line number in *.ipynb file when you forgot to put comma in proper place...).
Here is link to some of my repo where I use TeXify for which documentation was generated from README.tex.md file.
Update
Today 2020.12.13 I realised that TeXify plugin stop working - even after reinstallation :(
For automatic conversion upon push to GitHub, take a look at the TeXify app:
GitHub App that looks in your pushes for files with extension *.tex.md and renders it's TeX expressions as SVG images
How it works (from the source repository):
Whenever you push TeXify will run and seach for *.tex.md files in your last commit. For each one of those it'll run readme2tex which will take LaTeX expressions enclosed between dollar signs, convert it to plain SVG images, and then save the output into a .md extension file (That means that a file named README.tex.md will be processed and the output will be saved as README.md). After that, the output file and the new SVG images are then commited and pushed back to your repo.
I just published a new version of xhub, a browser extension that renders LaTeX (and other things) in GitHub pages.
Cons:
You have to install the extension once.
Pros:
No need to set up anything.
Just write Markdown with math
Display math:
```math
e^{i\pi} + 1 = 0
```
and line math $`a^2 + b^2 = c^2`$.
(Syntax like on GitLab.)
Works on light and dark background. (Math has text-color)
You can copy-and-paste the math just like text
As an example, check out this GitHub README:
You can get a continuous integration service (e.g. Travis CI) to render LaTeX and commit results to github. CI will deploy a "cloud" worker after each new commit. The worker compiles your document into pdf and either cuses ImageMagick to convert it to an image or uses PanDoc to attempt LaTeX->HTML conversion where success may vary depending on your document. Worker then commits image or html to your repository from where it can be shown in your readme.
Sample TravisCi config that builds a PDF, converts it to a PNG and commits it to a static location in your repo is pasted below. You would need to add a line that fetches pdfconverts PDF to an image
sudo: required
dist: trusty
os: linux
language: generic
services: docker
env:
global:
- GIT_NAME: Travis CI
- GIT_EMAIL: builds#travis-ci.org
- TRAVIS_REPO_SLUG: your-github-username/your-repo
- GIT_BRANCH: master
# I recommend storing your GitHub Access token as a secret key in a Travis CI environment variable, for example $GH_TOKEN.
- secure: ${GH_TOKEN}
script:
- wget https://raw.githubusercontent.com/blang/latex-docker/master/latexdockercmd.sh
- chmod +x latexdockercmd.sh
- "./latexdockercmd.sh latexmk -cd -f -interaction=batchmode -pdf yourdocument.tex -outdir=$TRAVIS_BUILD_DIR/"
- cd $TRAVIS_BUILD_DIR
- convert -density 300 -quality 90 yourdocument.pdf yourdocument.png
- git checkout --orphan $TRAVIS_BRANCH-pdf
- git rm -rf .
- git add -f yourdoc*.png
- git -c user.name='travis' -c user.email='travis' commit -m "updated PDF"
# note we are again using GitHub access key stored in the CI environment variable
- git push -q -f https://your-github-username:$GH_TOKEN#github.com/$TRAVIS_REPO_SLUG $TRAVIS_BRANCH-pdf
notifications:
email: false
This Travis Ci configuration launches a Ubuntu worker downloads a latex docker image, compiles your document to pdf and commits it to a branch called branchanme-pdf.
For more examples see this github repo and its accompanying sx discussion, PanDoc example,
https://dfm.io/posts/travis-latex/, and this post on Medium.
I have been looking around and found that this answer in another question works best for me. i.e. use githubcontent math renderer, e.g. to display:
Use this link
Beware of the latex needs to be url encoded, but otherwise work quite well for me.
If you are having issues with https://www.codecogs.com/latex/eqneditor.php, I found that https://alexanderrodin.com/github-latex-markdown/ worked for me. It generates the Markdown code you need, so you just cut and paste it into your README.md document.
You may also take a look on my tool latexMarkdown2Markdown which convert LaTeX to SVG and generate a table of content with chapter numbering.
Good news!
According to this blogpost, now GitHub supports Mathjax in readme files.
You can use in-line LaTeX inspired syntax using $ delimiters, or in-blocks using $$ delimiters.
Writing inline expressions:
This sentence uses $ delimiters to show math inline:
$\sqrt{3x-1}+(1+x)^2$
Writing expressions as blocks:
The Cauchy-Schwarz Inequality
$$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2
\right) \left( \sum_{k=1}^n b_k^2 \right)$$
Source: https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions
You can use markdowns, e.g.
![equ](https://latex.codecogs.com/gif.latex?log(y)=\beta_0&space;&plus;&space;\beta_1&space;x&space;&plus;&space;u)
Code can be typed here: https://www.codecogs.com/latex/eqneditor.php.
Edit: As germanium pointed out, it does not work for README.md but other git pages though no explanation is available.
My quick solution is this
step 1. Add latex to your .md file
$$x=\sqrt{2}$$
Note: math eqns must be in $$...$$ or \\(... \\).
step 2. Add the following to your scripts.html or theme file (append this code at the end)
<script type="text/javascript" async
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML">
Done!. See your eq. by loading the page.

How do I create some kind of table of content in GitHub wiki?

If you look here: http://en.wikipedia.org/wiki/Stack_Overflow
You'll notice there's a little "Content" section, if you click on one of the links, it will send you to a specific section on the page.
How do I do this in GitHub wiki? With Markdown or whatever they use?
It is nicely demonstrated in the Table of Contents of the Markdown Cheatsheet.
##### Table of Contents
[Headers](#headers)
[Emphasis](#emphasis)
...snip...
<a name="headers"/>
## Headers
If you hover over a Header in a GitHub Markdown file, you'll see a little link sample to the left of it, you can also use that link. The format for that link is <project URL#<header name>. The <header name> must be all lower case.
Since github cannot use TOC directly, but we have other alternatives.
You can automatically generate TOC via Online tool:
Generate TOC Table of Contents from GitHub Markdown or Wiki Online
or via Local tool:
github-markdown-toc
Visual Studio Code
If you happen to use Visual Studio Code, there is easy-to-use extension called Markdown All in One that can make the TOC for any .md file in an instant.
Just open Command Palette (Ctrl-Shift-P) -> Markdown: Create Table of Contents
Auto-update messes your edited TOC?
As an additional tip, you might want to turn the "automatic TOC updates on save" OFF by using
"markdown.extension.toc.updateOnSave": false,
in your Visual Studio Settings (Command Palette -> Preferences: Open Settings (JSON)).
One possible (semi-automated) solution is Eugene Kalinin's github-markdown-toc. This tool essentially crunches through your README.md file and snarfs out #'s headings to create a TOC.
Download the script https://github.com/ekalinin/github-markdown-toc
Feed your README.md to the script (as noted in Eugene's README.md)
cat README.md | bash github-markdown-toc
Cut and paste generated TOC and place it at the top of your README.md file
Note that this bash implementation only works on Linux (from what I can tell).
As a side note, there is a golang implementation and is probably more of a hassle to get working.
Update Aug. 2021:
After ToC in README (see March 2021 below), you now have:
Table of content for Wikis
For Wikis we now automatically generate a table of contents based on the Markdown headings.
As illustrated here:
Do you wiki?
We just added an automatic table of contents to the sidebar to help with navigation
You can now (March 2021) check out what the CEO of GitHub Nat Friedman just announced
GitHub now automatically creates a table of contents for your http://README.md files from your headers.
After much consideration, we made this a feature of the viewer, not a concern of the editor: no special markdown to insert.
So... it does not modify your markdown (README.md or other .md files) to insert, or update your text: it only provides a menu which allows quick access to your test sections based on markdown headers.
That may, or may not, what you are after.
https://github.com/jonschlinkert/markdown-toc
git clone your-repo.wiki.git (add the .wiki right before .git to clone the wiki
npm i -g markdown-toc
Insert <!-- toc --> (case sensitive) in your wiki's markdown
markdown-toc -i my-wiki-markdown.md (-i will edit it in place)
Profit
Update: I think maybe https://github.com/thlorenz/doctoc is more popular now.
Currently it's not possible to do that using markdown syntax (.md). There is ongoing unofficial discussion about automatically generating table of contents TOC on rendered markdown files like README.md which lists some of the ideas.
However there are some other workarounds such as:
Use AsciiDoc instead as per suggestion from this comment. For example:
:toc: macro
:toc-title:
:toclevels: 99
# Title
toc::[]
## A
### A2
## B
### B2
Check the example at littlebits/react-popover (README.adoc).
Online Table Of Content Generator (raychenon/play-table-of-contents)
arthurhammer/github-toc - browser extension that adds a table of contents to GitHub repos
If you are not in the position to stick with Markdown, you can do as below:
on GitHub/wiki: switch Markdown to MediaWiki. Use __TOC__ Syntax. See sample.
on GitHub/repo: switch Markdown to AsciiDoc. Use :toc: Syntax. See demo.
on GitHub/repo: switch Markdown to reStructuredText. Use .. contents:: Syntax.
However, using Markdown files in GitHub/repo, you can get it on GitHub Pages like in Wikipedia
when Jekyll is activated, it generates GitHub Pages using Kramdown by default
Kramdown comes with Table Of Content. Use {:toc} Syntax. See the explanation.
You can choose the Edit mode "MediaWiki" which will generate a toc for the headers, e.g.
== First ==
== Second ==
Due to the fact that github has it's own way of generating id=".." attributes in h1, h2, h3, etc... headers in html version after processing Markdown (for example Bitbucket use little different pattern of sluggifying headers title to id="slug") it is handy to don't reinvent the wheel and use library that reverse engineered this process.
I found one quite good library for this task called markdown-toc.
For me it seems the best solution because I always have installed node on my machine.
Just execute npx markdown-toc -i file.md.
And it looks like it is one of more popular tools for this task - at least in node.js ecosystem.
ls
cat <<EOF >> test.md | tee
## Table of Contents
<!-- toc -->
- old toc 1
- old toc 2
- old toc 3
<!-- tocstop -->
## abc
This is a b c.
## xyz
This is x y z.
EOF
ls
cat test.md
npx markdown-toc -i test.md
cat test.md
output:
Pandoc
The swiss army knife of markup:
cat README.md | pandoc --from markdown --toc -s --to markdown -
You can use mdtoc (I am the author).
Once installed, simply run:
mdtoc path/to/file.md
One more TOC markdown related tool implemented on the top of Perl (which is shipped with Linux/Git-for-Windows always and with Cygwin optionally, and there are no dependencies on extra packages)
https://github.com/ildar-shaimordanov/git-markdown-toc
I guess my tool works similar or almost similar to ekalinin/git-markdown-toc mentioned above by other people. I have never compared tham because his tool is implemented as Go-Lang which doesn't exist on my system. The main goal of my script is to provide the good solution in creating TOC locally -- no any connection to any exteranl hosts and so on, only read a local file (README.md, by default) and create the TOC and embed it to the file.
Example:
[Go to Delete](#delete_lines)
#delete_lines
code here, will be pointed here
See: https://guides.github.com/features/mastering-markdown/
And, to make a nested outline:
* 1\. [Go to Delete](#delete_lines)
* 1.1\. item
* 1.2\. item
* 1.2\. item
* 2\. item
See: https://meta.stackexchange.com/questions/85474/how-to-write-nested-numbered-lists
And for more info and complex linking:
https://stackoverflow.com/questions/6695439/how-to-link-to-a-named-anchor-in-multimarkdown#:~:text=In%20standard%20Markdown%2C%20place%20an,%5Blink%20text%5D(%23abcd)%20.

Version control for DOCX and PDF?

I've been playing around with git and hg lately and then suddenly it occurred to me that this kind of thing will be great for documents.
I've a document which I edit in DOCX and export as PDF. I tried using both git and hg to version control it and turns out with hg you end up tracking only binary and diff-ing isn't meaningful. Although with git I can meaningfully diff DOCX (haven't tried on PDF yet) I was wondering if there is a better way to do it than I'm doing it right now. (Ideally, not having to leave Word to diff will be the best solution.)
There are two different concepts here - one is "can the version control system make some intelligent judgements about the contents of files?" - so that it can store just delta information between revisions (and do things like assign responsibility to individual parts of a file).
The other is 'do I have a file comparison tool which is useful for the types of files I have in the version control system'. Version control systems tend to come with file comparison tools which are inferior to dedicated alternatives. But they can pretty much always be linked to better diff programs - either for all file types or specific ones.
So it's common to use, for example, Beyond Compare as a general compare tool, with Word as a dedicated Word document comparer.
Different version control systems differ as to how good people perceive them to be at handling 'binaries', but that's often as much to do with handling huge files and providing exclusive locking as it is to do with file comparison.
http://tortoisehg.bitbucket.io/ includes a plugin called docdiff that integrates Word and Excel diff'ing.
You can use Beyond Compare as external diff tool for hg. Add to/change your user mercurial.ini as:
[extdiff]
cmd.vdiff = c:/path/to/BCompare.exe
Then get Beyond Compare file viewer rule for docx.
Now you should be able to compare two versions of docx in Beyond Compare.
This article outlines the solution for Docx using Pandoc
While this post outlines solution for PDF using pdf2html.
Only for docx, I compiled instructions for multiple places here: https://gist.github.com/nachocab/6429893
# download docx2txt by Sandeep Kumar
wget -O docx2txt.pl http://www.cs.indiana.edu/~kinzler/home/binp/docx2txt
# make a wrapper
echo '#!/bin/bash
docx2txt.pl $1 -' > docx2txt
chmod +x docx2txt
# make sure docx2txt.pl and docx2txt are your current PATH. Here's a guide
http://shapeshed.com/using_custom_shell_scripts_on_osx_or_linux/
mv docx2txt docx2txt.pl ~/bin/
# set .gitattributes (unfortunately I don't this can't be set by default, you have to create it for every project)
echo "*.docx diff=word" > .git/info/attributes
# add the following to ~/.gitconfig
[diff "word"]
binary = true
textconv = docx2txt
# add a new alias
[alias]
wdiff = diff --color-words
# try it
git init
# create my_file.docx, add some content
git add my_file.docx
git commit -m "Initial commit"
# change something in my_file.docx
git wdiff my_file.docx
# awesome!
It works great on OSX
If you happen to use a Mac, I wrote a git merge driver that can use Microsoft Word and tracked changes to merge and show conflicts between any file types Word can read & write.
http://github.com/jasmas/wordMerge
I say 'if you happen to use a Mac' because the driver I wrote uses AppleScript, primarily to accomplish this task.
It'd be nice to add a vbscript version to the project, but at the moment I don't have a Windows environment for testing. Anyone with some basic scripting knowledge should be able to take a look at what I'm doing and duplicate it in vbscript, powershell or whatever on Windows.
I used SVN (yes, in 2020 :-)) with TortoiseSVN on Windows. It has a built-in function to compare DOCX files (it opens Microsoft Word in a mode where your screen is divided into four parts: the file after the changes, before the changes, with changes highlighted and a list of changes). Screenshot below (sorry for the Polish version of MS Word). I also checked TortoiseGIT and it also has this functionality. I've read that TortoiseHG has it as well.