DEV Community

jovica
jovica

Posted on

54 6

A Simple (Yet Powerful) Tip on Git and Vim

Here's a tip you might find useful if you work with git and you use Vim. I recently came up with it.

For example, I want to see a file in different branch while staying in my current branch(so without changing the branch). I could use command like:

git show branch_name:/path/to/file.pl
Enter fullscreen mode Exit fullscreen mode

But what if I want to see this file in Vim? It's easy, I could run a command like:

git show branch_name:/path/to/file.pl | vim -
Enter fullscreen mode Exit fullscreen mode

However, this way there's no syntax highlight, so we can fix this:

git show branch_name:/path/to/file.pl | vim - -c 'set syntax=perl'
Enter fullscreen mode Exit fullscreen mode

That's nice :) now my Perl file is properly highlighted.

Okay, but what if I work with Perl, and Python, and Bash, etc. It's not very handy to type all of this every time.

Here's one solution - you could create aliases:

alias vim.py="vim - -c 'set syntax=python'"
alias vim.pl="vim - -c 'set syntax=perl'"
Enter fullscreen mode Exit fullscreen mode

So next time you need to see a Python file in different branch than your current one, you could run:

git show branch_name:/path/to/file.py | vim.py
Enter fullscreen mode Exit fullscreen mode

I hope you find this useful.


I share tips like this in Mastering Vim Quickly newsletter at http://masteringvim.com.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (5)

Collapse
 
gypsydave5 profile image
David Wickes

Maybe better if instead of an alias you wrote a short bash script that could take an argument for the filetype? Something like (call it vimtype).

vim - -c "set syntax=$1"

So...

git show branch_name:/path/to/file.py | vimtype python

Just a thought

Collapse
 
jovica profile image
jovica

I like it, cool idea too! Thanks.

Collapse
 
lakshmankumar12 profile image
Lakshman Kumar Narayanan

Also please checkout [vim-fugitive|github.com/tpope/vim-fugitive].

Have the interested file from the current branch open in vim. Then :Gedit some_other_branch:% opens the file as in the other branch, with syntax highlighting!

Collapse
 
rcreasi profile image
Randy Creasi

vim-fugitive transformed the way I work. Can't recommend it highly enough.

Collapse
 
ferricoxide profile image
Thomas H Jones II

For me:

vim -c 'set syntax=<TYPE>' <( git show <BRANCH>:PATH/TO/FILE )

Feels more natural. Basically, I'm still saying "vim this".

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay