derek
derek

Reputation: 10227

How to display line numbers using GitHub Flavored Markdown "code"?

I know I can use "code" in GitHub Flavored Markdown to highlight a code snippet. But I am not able to display line numbers for a snippet. Is there a way to do so?

```javascript
var s = "JavaScript syntax highlighting";
alert(s);
```

I want a line number to be put at the beginning of each line, like this:

1    var s = "JavaScript syntax highlighting";
2    alert(s);

Upvotes: 91

Views: 85519

Answers (8)

Eduardo Alvim
Eduardo Alvim

Reputation: 341

I use RStudio with RMarkdown to render my Markdown (.md) files. It works great. Using the RMarkdown, the specification is made this way:

```{.javascript .numberLines .lineAnchors}
var s = "JavaScript syntax highlighting";
alert(s);
```

Yes, there are many markdown editors available and I'm not sure that this will work with all the editors, but RStudio/RMarkdown is a really great tool, which I use since a long time ago (IMHO).

Upvotes: 8

Simon B
Simon B

Reputation: 587

Just add an = after the language you choose !

```java=
java code exemple:
int i = 5
```java=

Upvotes: -3

Callum Atwal
Callum Atwal

Reputation: 165

Although it is not available in GitHub as the question asks, I have discovered today if you add an = sign after the opening line, on some Markdown editors, it gives the desired result.

eg:

```javascript=
var s = "JavaScript syntax highlighting";
alert(s);
```

This works on Markdown editors such as HackMD

See your example on HackMD

Upvotes: 8

jseteny
jseteny

Reputation: 420

You can get something similar that you need using awk '{printf("% 4d %s\n", NR, $0)}' StartDsl.scala where StartDsl.scala is your source code file. Paste the result between

```scala
<your code here>
```

Upvotes: 6

Birch
Birch

Reputation: 217

As a hack, you could save a pic of your code at https://carbon.now.sh and post it; they support line numbers as an option.

Upvotes: 5

Ang
Ang

Reputation: 23

Now here is the solution for adding line numbers in Markdown.

https://shd101wyy.github.io/markdown-preview-enhanced/#/markdown-basics?id=line-numbers

You can enable line number for a code block by adding line-numbers class.

Upvotes: -6

Vinay Prajapati
Vinay Prajapati

Reputation: 7514

So, you will need to help yourself by adding css to your html page. As a code goes into <pre> </pre> block in markdown.

You could apply your logic to this block to put line number against each line.

See https://codepen.io/heiswayi/pen/jyKYyg for reference.

Upvotes: 5

denysdovhan
denysdovhan

Reputation: 986

As you may noticed in Markdown Cheatsheet, GitHub does not show line numbers in code blocks.

Upvotes: 46

Related Questions