Create a Diff in Markdown to Show What Has Changed in a Code Snippet

Ali Spittel
InstructorAli Spittel
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

You can create diffs in markdown to show what has changed in a code snippet. I use this in blog posts to highlight changed lines for readers. This works for code snippets in most markdown packages and on Dev.to.

To show a line of code changing in a function, you can do this:

function addTwoNumbers (num1, num2) {
-  return 1 + 2
+  return num1 + num2
}

First, instead of specifying the programming language, use diff after the backticks. Then at the beginning of any lines of code you want to show as removed, add a -. At the beginning of any lines of code you want to show as added, add a +.

The code would look like this:

```diff
function addTwoNumbers (num1, num2) {
-  return 1 + 2
+  return num1 + num2
}
```

Ali Spittel: [0:00] I have two code snippets in a Markdown file, and I want to show readers what has changed between the two files. I can use a dif to do so. I can write dif after three backticks that start a code snippet.

[0:14] Then I can add a plus sign before any line of code that I want to show as added. I can add a minus sign before any line of code that I want to show as taken away.

[0:27] I'll use the Markdown preview tool to see what this looks like. You can see that lines that I want to show as deleted show in red, and lines that I want to show as added are highlighted in green.

[0:39] This works in most Markdown renders including GitHubs and Dev.tos. Just like that, you can show a user what has changed from code snippet to code snippet.