Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git ignore trailing whitespace in markdown files only

I have a markdown file with lines that have trailing whitespace (which is correct and should be commited). I'm unable to add these changes using git add -p to the index because git complains about trailing whitespace. They are added correctly if I use git add -A, but I want it to work with git add -p.

I have in my ~/.gitconfig:

[core]
  whitespace = trailing-space,space-before-tab

This has been working fine since for the most part I DO want to warn on trailing whitespace (it is incorrect in HTML, JS and Ruby files).

How do I ignore the trailing whitespace in Markdown files only?

like image 246
Devon Parsons Avatar asked Feb 07 '23 01:02

Devon Parsons


2 Answers

In a .gitattributes file add the following:

**/*.md  -whitespace

https://git-scm.com/docs/gitattributes#_checking_whitespace_errors

More specifically you could instead do the following:

**/*.md  whitespace=space-before-tab

(dropping the trailing-space for markdown files.)

Treat .gitattributes in the same way you do .gitignore and check it into the repo.

like image 159
Sukima Avatar answered Feb 08 '23 14:02

Sukima


Use this in .gitattributes:

**/*.md text whitespace=-cr-at-eol,-trailing-space

**/*.md whitespace=space-before-tab does not work. Try this in cmd.exe:

$ git config --show-origin --get core.whitespace
file:C:/Users/kevin/.gitconfig  trailing-space,space-before-tab,cr-at-eol

$ git init .
Initialized empty Git repository in trailing/.git/

$ cat > README.md
Trailing space here:
check it

$ git add README.md

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here: 

$ echo **/*.md  -whitespace > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: unset

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904

$ echo **/*.md  whitespace=space-before-tab > .gitattributes

$ git check-attr --all -- README.md
README.md: whitespace: space-before-tab

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
README.md:1: trailing whitespace.
+Trailing space here:

$ echo **/*.md text whitespace=-cr-at-eol,-trailing-space > .gitattributes

$ git diff-index --check --cached 4b825dc642cb6eb9a060e54bf8d69288fbee4904
like image 43
Kevin Smyth Avatar answered Feb 08 '23 14:02

Kevin Smyth