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

后端 未结 6 1640
攒了一身酷
攒了一身酷 2020-12-04 10:54

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

" the mappi         


        
相关标签:
6条回答
  • 2020-12-04 11:28

    Btw... if your primary problem is about commenting... you should check out 'nerdcommenter' plugin, its the fastest way to comment/uncomment your code in java/c/c++/python/dos_batch_file/etc etc.

    0 讨论(0)
  • 2020-12-04 11:35

    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> ...
    
    0 讨论(0)
  • 2020-12-04 11:37

    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>
    
    0 讨论(0)
  • 2020-12-04 11:39

    I prefer to have my configuration 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 doesn't clear set autocmds when you source your vimrc, so starting vim, changing something in your vimrc and running :so ~/.vimrc would define autocmds twice. That's why the bindings are grouped and cleared with autocmd! group_name. You can read more here.

    Since mappings are applied to every buffer by default, and you want to change them for buffers matching the filetype only, the <buffer> modifier is in there, limiting the mappings to the local buffer.

    0 讨论(0)
  • 2020-12-04 11:42

    I recommend the .../ftplugin/<filetype>.vim approach that freitass suggests, but in your specific case Vim Commentary will solve all of this for you.

    0 讨论(0)
  • 2020-12-04 11:44

    This is only a partial answer for people coming here having difficulties getting any ftplugin scripts working, but remember that your .vimrc (or a file that it sources) should contain

    filetype plugin on
    

    or

    :filetype plugin on
    

    for filetype-plugins to be executed when a file of a given type is loaded.

    0 讨论(0)
提交回复
热议问题