Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map keys in vim differently for different kinds of buffers

Tags:

vim

The problem i am facing is that i have mapped some keys and mouse events for seraching in vim while editing a file. But those mappings impact the functionality if the quickfix buffer.

I was wondering if it is possible to map keys depending on the buffer in which they are used.

EDIT - I am adding more info for this question Let us consider a scenario. I want to map <C-F4> to close a buffer/window. Now this behavior could depend on a number of things.

If i am editing a buffer it should just close that buffer without changing the layout of the windows. I am using buffkil plugin for this.

It does not depend on extension of file but on the type of buffer. I saw in vim documentation that there are unlisted and listed buffer. So if it is listed buffer it should close using bufkill commands.

If it is not a listed buffer it should use <c-w>c command to close buffer and changing the window layout.

I am new at writing vim functions/scripts, can someone help me getting started on this

like image 363
Yogesh Arora Avatar asked Mar 12 '10 16:03

Yogesh Arora


2 Answers

function KillBuffer()
    if &buflisted
         " bufkill command here
    else
         execute "normal! \<C-w>c"
    endif
endfunction
noremap <C-F4> :call KillBuffer()<CR>

Put this in your .vimrc Or, if you want to handle quickfix window as unlisted buffers (in my Vim it is listed):

function KillBuffer()
    if &buflisted && !&filetype=="qf"
         " bufkill command here
    else
         execute "normal! \<C-w>c"
    endif
endfunction
noremap <C-F4> :call KillBuffer()<CR>

According to the manual, you could replace execute "normal! \<C-w>c" with simpler close! in the above scripts.

like image 91
ZyX Avatar answered Sep 24 '22 01:09

ZyX


You can create filetype specific settings. First, in your vimrc file, make sure filetype plugins are enabled by adding

filet plugin on

Then make a filetype specific plugin. Under Unix create a file called ~/.vim/after/ftplugin/[file-type-name].vim and put your mapping in there. In Windows the directory is $HOME/vimfiles/after/ftplugin. The [file-type-name] is the type detected by Vim, sometimes the same as the filename extension, e.g c.vim, python.vim, etc. Vim can tell you what the type is after you open the file if you enter

:echo &ft

like image 24
Steve K Avatar answered Sep 24 '22 01:09

Steve K