Yan Han's blog

On Computer Technology

20 Feb 2018

Vim abbreviations for a specific file

Tags

vim

Recently I came across Bram Moolenaar’s article Vim: Seven habits of effective text editing and learnt about vim abbreviations. Essentially, vim abbreviations allow you to specify shortform words that vim will automatically expand to their long form. For instance, with the following in your vimrc:

ab dev developer

Whenever you type the word dev followed by a space / enter / punctuation mark, vim will automatically expand it to developer. I am not entirely certain of the rule that vim uses to expand the abbreviation, but it seems to me that vim does it on a word boundary basis. Hence you do not have to be afraid that you cannot type devops for fear that it will be expanded to developerops.

This is pretty useful and can save a lot of typing. There are other pieces of wisdom in the article and I highly encourage you to read it.

How to have file specific vim abbreviations

Which brings us to the meat of this post. How do we have abbreviations that apply to a specific file? Some Googling led to this Unix & Linux Stack Exchange answer and here’s some example code on how to do it:

au BufRead,BufNewFile /path/to/file call YourAbbrevFunction()
function YourAbbrevFunction()
  ab dev developers
  " define your other abbreviations here
endfunction

Instructions

  1. Copy and paste the above code to your vimrc file
  2. Define all your desired abbreviations in the YourAbbrevFunction vim function
  3. Change the /path/to/file to the file you want the abbreviations to apply to
  4. If you have an existing vim session editing the /path/to/file, you will need to quit and start it again for the abbreviations to apply

Enjoy!

References

Disclaimer: Opinions expressed on this blog are solely my own and do not express the views or opinions of my employer(s), past or present.

comments powered by Disqus