Apply Customizations to Certain Types of Files

Our preferences may vary from one type of file to another. For example, suppose that we work with a house style that advises two spaces for indentation in Ruby and four-column-wide tabs for JavaScript. We could apply these settings by putting the following lines in our vimrc:

 if​ has(​"autocmd"​)
 filetype​ ​on
  autocmd FileType ​ruby​ ​setlocal​ ​ts​=2 ​sts​=2 ​sw​=2 et
  autocmd FileType javascript ​setlocal​ ​ts​=4 ​sts​=4 ​sw​=4 noet
 endif

The autocmd declaration tells Vim to listen for an event and to execute the specified commands whenever that event fires (:autocmd). In this case we’re listening for the FileType event, which is triggered ...

Get Practical Vim, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.