Can you have bindings to a specific file type in Vim?

In my .vimrc file, I have a key binding for comments that insert double slashes ( // ) before the line

 " the mappings below are for commenting blocks of text :map <CG> :s/^/\/\//<Esc><Esc> :map <CT> :s/\/\/// <Esc><Esc> 

However, when I edit Python scripts, I want to change this to a # sign for comments

I have a Python.vim file in my .vim/ftdetect , which also has settings for tabs, etc. What is the code to override key bindings, if possible, so I use Python:

 " the mappings below are for commenting blocks of text :map <CG> :s/^/#/<Esc><Esc> :map <CT> :s/#/ <Esc><Esc> 
+68
vim
May 26 '11 at 3:22 a.m.
source share
5 answers

The ftdetect folder is for file type detection scripts. File type plugins must be located inside the ftplugin folder. The file type must be included in the file name in one of the following three forms:

  • .../ftplugin/<filetype>.vim
  • .../ftplugin/<filetype>_foo.vim
  • .../ftplugin/<filetype>/foo.vim

For example, you can match comments for the cpp file type by typing the following inside .../ftplugin/cpp_mine.vim :

 :map <buffer> <CG> :s/^/\/\//<Esc><Esc> :map <buffer> <CT> :s/\/\/// <Esc><Esc> 
+60
May 26 '11 at 3:45
source share

You can use :map <buffer> ... for local mapping only for the active buffer. This requires that your Vim be compiled using +localmap .

So you can do something like

 autocmd FileType python map <buffer> <CG> ... 
+71
May 26 '11 at 3:32
source share

Btw ... if your main problem is commenting ... you should check out the "nerdcommenter" plugin, this is the fastest way to comment / uncomment your code in java / c / C ++ / python / dos_batch_file / etc etc.

+3
May 24 '14 at 8:41
source share

This is only a partial answer for people coming here who have difficulty working with any ftplugin scripts, but remember that your .vimrc (or the file that it contains) must contain

 filetype plugin on 

or

 :filetype plugin on 

so that filetype plugins are executed when a file of this type is loaded.

0
Jun 27 '18 at 23:57
source share

I prefer my configuration to be in a single file, so I use the autocmd approach.

 augroup pscbindings autocmd! pscbindings autocmd Filetype purescript nmap <buffer> <silent> K :Ptype<CR> autocmd Filetype purescript nmap <buffer> <silent> <leader>pr :Prebuild!<CR> augroup end 

Vim does not clear set autocmds when you create vimrc source code, so run vim, change something in your vimrc and run :so ~/.vimrc will detect autocmds twice. This is why bindings are grouped and cleared using autocmd! group_name autocmd! group_name autocmd! group_name autocmd! group_name you can read more here .

Since mappings are applied to each buffer by default, and you want to change them for buffers that match only the file type, the <buffer> modifier is there, restricting mappings to the local buffer.

0
Jan 09 '19 at 10:28
source share



All Articles