Reputation: 10882
I am writing a rudimentary Vim template for Java files that creates a bare skeleton class when I create a new file with the .java extension.
Example:
vim Banana.java
Vim creates a file including code like this:
public class TODO {
public static void main(String[] args) {
// ...
My objective is to change my default class name, TODO
, to the name of the file without the extension so that:
vim Coconut.java
creates:
public class Coconut {
rather than:
public class TODO {
How can I achieve that, please? I have searched the site and there are scripts that extract the name in a variable and perform :substitute in the right place, but I don't know how to locate the right place and position the filename there.
I read my template files by extension from my .vimrc:
autocmd BufNewFile * silent! 0r $HOME/vimfiles/templates/%:e.vim_template
or:
autocmd BufNewFile * silent! 0r $HOME/.vim/templates/%:e.vim_template
Thanks!
Upvotes: 4
Views: 2180
Reputation: 4210
I'd take a look at snipmate (vim.org, github). It's a generic extension for boilerplate code, comes with a number of built-in recipes for Java (which you can browse here to get a feel for it), and is ideal for this kind of stuff.
With it, you can type in a keyword, hit tab, and have the keyword expanded into your boilerplate code. So you could type stdclass->
and get what you're asking for.
The snippet can have vim expressions embedded (like Filename()
); you can tab through important points in the expanded code, and it's useful for smaller snippets too (like getters & setters, try/catch/finally, toString, etc.)
It's easy to use, easy to customize, and in a boilerplate-heavy language like Java, it's a godsend.
Upvotes: 1
Reputation: 80011
I believe that this might help? http://vim.wikia.com/wiki/Insert_current_filename
With this you can get the current filename:
expand("%:t:r")
Specifically, you are probably looking for this:
%s/TODO/\=expand("%:t:r")/g
A full example:
function! NewFile()
silent! 0r $HOME/vimfiles/templates/%:e.vim_template
s/FILENAME/\=expand("%:t:r")
endfunction
autocmd BufNewFile * call NewFile()
You could also give something like tSkeleton a try, I've never tried myself but it seems to solve this problem for you.
Upvotes: 4