Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have file type-specific key bindings in Vim?

Tags:

vim

In my .vimrc file, I have a key binding for commenting out that inserts double slashes (//) at the start of a line:

" the mappings below are for commenting blocks of text :map <C-G> :s/^/\/\//<Esc><Esc> :map <C-T> :s/\/\/// <Esc><Esc> 

However, when I’m editing Python scripts, I want to change that to a # sign for comments

I have a Python.vim file in my .vim/ftdetect folder that also has settings for tab widths, etc. What is the code to override the keybindings if possible, so that I have Python use:

" the mappings below are for commenting blocks of text :map <C-G> :s/^/#/<Esc><Esc> :map <C-T> :s/#/ <Esc><Esc> 
like image 570
James Avatar asked May 26 '11 03:05

James


People also ask

Does vim allow for custom key bindings?

Creating a set of key bindings that is familiar, eases the learning curve of any new editor, and the flexibility vim allows in this configuration makes it easy to not only leverage the power of vim, but also make it feel like a familiar old friend.

How do I change the filetype in vim?

As other answers have mentioned, you can use the vim set command to set syntax. :set syntax=<type> where <type> is something like perl , html , php , etc. There is another mechanism that can be used to control syntax highlighting called filetype , or ft for short.

What is key bindings in vim?

Understanding the structure of Key binding So that means you can have the same key mapped to different commands depending on the mode. That is really flexible and powerful. Vim allows you to basically map in almost every mode such as normal, insert, visual, command, and any other existing modes.

What is filetype vim?

vim which is used to determine the "type" of a file. For example, while editing example.py the command :set ft? should display filetype=python if :filetype indent plugin on has been used. The file type determines whether any plugins for scripts, indenting rules, or syntax highlighting are loaded.


2 Answers

You can use :map <buffer> ... to make a local mapping just for the active buffer. This requires that your Vim was compiled with +localmap.

So you can do something like

autocmd FileType python map <buffer> <C-G> ... 
like image 198
hammar Avatar answered Oct 05 '22 23:10

hammar


The ftdetect folder is for scripts of filetype detection. Filetype plugins must be inside the ftplugin folder. The filetype 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 instance, you can map comments for the cpp filetype putting the following inside the .../ftplugin/cpp_mine.vim:

:map <buffer> <C-G> :s/^/\/\//<Esc><Esc> :map <buffer> <C-T> :s/\/\/// <Esc><Esc> 
like image 35
freitass Avatar answered Oct 05 '22 21:10

freitass