user2138149
user2138149

Reputation: 16715

vim execute command depending on file type

How can I get vim to execute a command depending on the file type?

Recently I have been editing a lot of Python files and comments autoindent to the 0th column.

One way to fix this is to run the command inoremap # X#<left><backspace><right>

How can I get this command to run every time I open a python (*.py) file for editing?

Upvotes: 4

Views: 4423

Answers (2)

D. Ben Knoble
D. Ben Knoble

Reputation: 4673

TL;DR

Use vim's filetype plugin mechanism.

File-type specific code

There are (at least) two solutions to this, with one preferable to the other.

autocmd FileType

This has already been posted as an answer, but the general form is

augroup your_group
  autocmd!
  autocmd FileType python your good code
augroup END

This works, and has the advantage of grouping code in your vimrc.

But there is a second, more powerful, probably more performant alternative. It is my preferred solution.

after/ftplugin

I've written extensively about using filetype plugins in vim.

The gist of it is that you need filetype detection and plugins (filetype plugin on at a minimum, though you may want filetype plugin indent on). Then you drop filetype specific code in ~/.vim/after/ftplugin/<filetype>.vim (or a few variants, see :h add-filetype-plugin, :h ftplugin-name, :h ftplugin).

So ultimately,

" ~/.vim/after/ftplugin/python.vim
inoremap # X#<left><backspace><right>

A few notes

It is a good practice to set b:undo_ftplugin properly: it helps (trust me). You can borrow my undo script on Github.

Consider using <buffer>, -buffer, setlocal, and <LocalLeader> where possible. This is for local stuff, after all.

On power

A script gives you more flexibility than a single line of autocommands. You have to jump through more hoops to do anything complex in autocommands, where in a script they can just sit. Besides, you feel more like you're writing a program (which you are) than a one off config.

The modularity is also perfect for organization: all your python customization code is in one place.

And it's a lot less typing :)

On performance

I have not measured anything. Don't shoot me.

Having lots of autocommands can slow down vim, because they have to be checked when their events fire. Rather than clog up the autocommands with filetype stuff, use a file that is already going to be sourced for you (an ftplugin).

By piggybacking on an existing customization mechanic, you get all the benefit and none of the risk. Again, it is almost certainly more efficient to let vim source a file on demand for you then to try to reimplement it's ftplugin wheel.

Upvotes: 5

dlmeetei
dlmeetei

Reputation: 10381

Does this solve your issue?

au FileType python inoremap # X#<left><backspace><right>

This autocommand runs your mapping for filetype python

Upvotes: 1

Related Questions