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 3 years ago
Updated 3 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.

egghead
egghead
~ 10 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today