Better hunk headers for markdown in git
When you make many changes throughout a file, git
will group them in, so called, “hunks”. Typically, the changes of a single hunk will all occur within a single function. For C-like files git is intelligent enough to add a line at the top of the hunk (after @@...@@
) that shows you the name of the function. It finds out the name of the function with a regex defined for the type of the edited file. There are many predefined regexes (even for LaTeX) in git. Unfortunately there is no predefined regex for markdown files.
Luckily, you can define your own regexes to be placed at the top of a “hunk” by defining a xfuncname
for the file type. The code snippet below show you how you can make likes starting with #
(headers in markdown) become the header of the hunk, if the file is of type “md” for diffing according to git.
[diff "md"]
xfuncname="^#.*"
You can put this in your ~/.gitconfig
if you want it defined in all your repos, or you can specify it for one repo only in $repo/.git/config
.
To let git know that files ending in .md
are of diffing type “md” the following line should be added to your $repo/.gitattributes
. If you don’t want to share this setting, put it in $repo/.git/info/attributes
. Put it in $XDG_CONFIG_HOME/git/attributes
(probably ~/.config/git/attributes
) if you want it in all your repos.
*.md diff=md
Learn more about this in the gitattribute documentation page (man gitattributes
).
Example result
What was
...
@@ -274,7 +231,7 @@ this is some example prose text not much interesting here
except this line git shows you for context, but where is it located? Well,`git`
+shows the name of the section after the `@@`, because it understands markdown.
-does not understand how markdown works, so it's not very helpfull.
now becomes:
...
@@ -274,7 +231,7 @@ ## Getting `git` to understand markdown
except this line git shows you for context, but where is it located? Well,`git`
+shows the name of the section after the `@@`, because it understands markdown.
-does not understand how markdown works, so it's not very helpfull.
Bonus
Want to see the whole function/section that was edited using git? Use git diff --function-context
or more cryptic:
git diff -W