Vim Hotkeys For Specific File

4

3

Is it possible to set hotkey for specific file types in vim.

For example, if I am editing a .java file, I'd like vim to run javac .java when I press 5.

Is this possible?

vonhogen

Posted 2009-09-28T07:05:46.233

Reputation: 1 949

Answers

8

~/.vimrc

autocmd FileType java map <F5> :! javac %<cr>

More info about key mapping and external commands.

Andrejs Cainikovs

Posted 2009-09-28T07:05:46.233

Reputation: 2 611

is it possible to remove the extension of the file? so that I can do like java %(remove .java)? – vonhogen – 2009-09-28T08:01:21.753

I doubt so, but you can make a shortcut to a script which will strip the extension and execute javac on the result. – Andrejs Cainikovs – 2009-09-28T08:05:59.873

2@karmic: Use something like autocmd FileType java map <F5> :exe '! javac ' . expand('%:r')<CR> See :help expand() for more information. – Al. – 2009-09-28T12:24:00.860

4

(I fail to understand the point of the dichotomy between SO and SU for such questions... Anyway:) Your question has already been answered, a few days later, on SO: ftplugins + local mappings/abbreviations/commands are the way to go.

Regarding javac call, Just use %< to obtain the filename without the extension. A first correct mapping thus becomes:

:nnoremap <buffer> <f5> :!javac %<<cr>

But prefer instead to rely on the quickfix mode with:

:setlocal makeprg=javac\ $*
:nnoremap <buffer> <f5> :make %<<cr>

Luc Hermitte

Posted 2009-09-28T07:05:46.233

Reputation: 1 575

3

I don't have any direct experience writing anything like this from scratch with Vim, but here's what you'll want to look for examples to follow.

You probably want a filetype plugin (ftplugin) for .java files:

A filetype plugin is like a global plugin, except that it sets options and defines mappings for the current buffer only. See |add-filetype-plugin| for how this type of plugin is used.

And use it with a mapleader+hotkey:

To define a mapping which uses the "mapleader" variable, the special string "" can be used. It is replaced with the string value of "mapleader". If "mapleader" is not set or empty, a backslash is used instead. ... To define a mapping which uses the "mapleader" variable, the special string "" can be used. It is replaced with the string value of "mapleader". If "mapleader" is not set or empty, a backslash is used instead.

You might have a look at the Vim JDE scripts, or this guide on configuring Vi(m) for Java development. This page has some information on using javac in Vim.

jtimberman

Posted 2009-09-28T07:05:46.233

Reputation: 20 109