├── README.md └── ftplugin └── java └── javafmt.vim /README.md: -------------------------------------------------------------------------------- 1 | # vim-javafmt 2 | 3 | :JavaFmt 4 | 5 | vim plugin for java code format. similar to `:GoFmt`. 6 | 7 | you need to put `google-java-format-0.1-SNAPSHOT.jar` into `~/.vim/lib`. 8 | 9 | ## How to build google-java-format-0.1-SNAPSHOT.jar 10 | 11 | $ git clone https://github.com/google/google-java-format.git 12 | $ cd google-java-format/ 13 | $ mvn clean package --projects core 14 | 15 | If failed to build, let's skip tests. 16 | 17 | $ mvn package --projects core -DskipTests 18 | 19 | You will get `core/target/google-java-format-0.1-SNAPSHOT.jar` 20 | -------------------------------------------------------------------------------- /ftplugin/java/javafmt.vim: -------------------------------------------------------------------------------- 1 | if !executable('java') 2 | finish 3 | endif 4 | 5 | if !exists("g:javafmt_program") 6 | let g:javafmt_program = 'java -jar ' . globpath(&rtp, 'lib/google-java-format*.jar') 7 | endif 8 | 9 | if !exists("g:javafmt_options") 10 | let g:javafmt_options = '' 11 | endif 12 | 13 | function! s:javafmt(...) abort 14 | if empty(globpath(&rtp, 'lib/google-java-format*.jar')) 15 | echohl ErrorMsg 16 | redraw 17 | echomsg "Please download google-java-format and place in .vim/lib" 18 | echohl None 19 | return 20 | endif 21 | call setqflist([]) 22 | if len(a:000) == 0 23 | let lines = system(g:javafmt_program . ' ' . g:javafmt_options . ' - ', getline(1, '$')) 24 | let lines = join(map(split(lines, "\n"), 'substitute(v:val, "^:", expand("%:gs!\\!/!") . ":", "g")'), "\n") 25 | else 26 | let files = [] 27 | for arg in a:000 28 | let files += split(expand(arg), "\n") 29 | endfor 30 | let files = map(files, 'shellescape(expand(v:val))') 31 | let lines = system(g:javafmt_program . ' ' . g:javafmt_options . ' ' . join(files, ' ')) 32 | endif 33 | if v:shell_error == 0 34 | let pos = getcurpos() 35 | silent! %d _ 36 | call setline(1, split(lines, "\n")) 37 | call setpos('.', pos) 38 | else 39 | cexp lines 40 | endif 41 | if len(getqflist()) > 0 42 | copen | cc 43 | else 44 | cclose 45 | endif 46 | endfunction 47 | 48 | command! -nargs=* -complete=file JavaFmt call javafmt() 49 | --------------------------------------------------------------------------------