Search code examples
vimexecuteautostartautocmd

Launch (:normal) command on vim start with .java files


I want to put line in my .vimrc file so that it will fold the /* ... */ like comments on autostart with *.java files.

So far I have came up with this but it does not want to work (although the command works in vim)

autocmd BufReadPre,BufReadPost,FileReadPre,FileReadPost *.java execute ":normal :%g/\/\*/normal! zf%"

Solution

    • The :global command already is an Ex command; there's no need for :normal (which is for stuff like j, zf, /). This should work:
    :autocmd BufReadPre,BufReadPost,FileReadPre,FileReadPost *.java %g/\/\*/normal! zf%
    
    • You probably don't need to run this both before and after reading a file.
    • Vim can already detect the filetype; why duplicate the file pattern for Java files?! Better use the FileType event:
    :autocmd FileType java %g/\/\*/normal! zf%
    
    • Based on your previous question, it looks like you want to set up elaborate manual folding. That's rather unusual, and I would recommend against it. Java has built-in folding based on syntax highlighting (though not for comment blocks, but you can grab that from syntax/c.vim); you enable it via
    :setlocal foldmethod=syntax
    

    If you really need custom folding, :help fold-expr is the way to go.