Skip to content

Commit 1552a16

Browse files
authored
Merge pull request #78 from Kashomon/master
Add a google-java formatter.
2 parents 5ede026 + 1e5ad7a commit 1552a16

File tree

10 files changed

+157
-21
lines changed

10 files changed

+157
-21
lines changed

README.md

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ helpfiles in the `doc/` directory. The helpfiles are also available via
1818
* Go (gofmt)
1919
* [GN](https://www.chromium.org/developers/gn-build-configuration) (gn)
2020
* HTML (js-beautify)
21+
* Java (google-java-format or clang-format)
2122
* JavaScript (clang-format)
2223
* JSON (js-beautify)
2324
* Proto (clang-format)
@@ -62,6 +63,7 @@ call vundle#end()
6263
call glaive#Install()
6364
" Optional: Enable codefmt's default mappings on the <Leader>= prefix.
6465
Glaive codefmt plugin[mappings]
66+
Glaive codefmt google_java_executable="java -jar /path/to/google-java-format-VERSION-all-deps.jar"
6567
```
6668

6769
Make sure you have updated maktaba recently. Codefmt depends upon maktaba
@@ -80,13 +82,21 @@ augroup autoformat_settings
8082
autocmd FileType go AutoFormatBuffer gofmt
8183
autocmd FileType gn AutoFormatBuffer gn
8284
autocmd FileType html,css,json AutoFormatBuffer js-beautify
85+
autocmd FileType java AutoFormatBuffer google-java-format
8386
autocmd FileType python AutoFormatBuffer yapf
8487
" Alternative: autocmd FileType python AutoFormatBuffer autopep8
8588
augroup END
8689
```
8790

91+
# Configuring formatters
8892

89-
# Installing and configuring formatters
93+
Most formatters have some options available that can be configured via
94+
[Glaive](https://www.github.com/google/vim-glaive)
95+
You can get a quick view of all codefmt flags by executing `:Glaive codefmt`, or
96+
start typing flag names and use tab completion. See `:help Glaive` for usage
97+
details.
98+
99+
# Installing formatters
90100

91101
Codefmt defines several built-in formatters. The easiest way to see the list of
92102
available formatters is via tab completion: Type `:FormatCode <TAB>` in vim.
@@ -99,31 +109,28 @@ trigger formatters via key mappings and/or autocommand hooks. See
99109
vroom/main.vroom to learn more about formatting features, and see
100110
vroom/FORMATTER-NAME.vroom to learn more about usage for individual formatters.
101111

102-
Most formatters have some options available that can be configured via Glaive.
103-
You can get a quick view of all codefmt flags by executing `:Glaive codefmt`, or
104-
start typing flag names and use tab completion. See `:help Glaive` for usage
105-
details.
106-
107112
## Creating a New Formatter
108113

109114
Assume a filetype `myft` and a formatter called `MyFormatter`. Our detailed
110115
guide to creating a formatter [lives
111116
here](https://github.com/google/vim-codefmt/wiki/Formatter-Integration-Guide).
112117

113-
* Create an issue for your new formatter and discuss! Once there's consensus,
114-
continue onward.
118+
* Create an issue for your new formatter and discuss!
115119

116120
* Create a new file in `autoload/codefmt/myformatter.vim` See
117121
`autoload/codefmt/buildifier.vim for an example. This is where all the
118122
logic for formatting goes.
119123

120-
* Register the formatter with:
124+
* Register the formatter in
125+
[plugin/register.vim](plugin/register.vim)
126+
with:
121127

122128
```vim
123129
call s:registry.AddExtension(codefmt#myformatter#GetFormatter())
124130
```
125131
126-
* Create a flag in instant/flags.vim
132+
* Create a flag in
133+
[instant/flags.vim](instant/flags.vim)
127134
128135
```vim
129136
""
@@ -134,6 +141,8 @@ here](https://github.com/google/vim-codefmt/wiki/Formatter-Integration-Guide).
134141
* Create a [vroom](https://github.com/google/vim-vroom) test named
135142
`vroom/myformatter.vroom` to ensure your formatter works properly.
136143
144+
* Update the README.md to mention your new filetype!
145+
137146
That's it! Of course, the complicated step is in the details of
138147
`myformatter.vim`.
139148

autoload/codefmt.vim

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ endfunction
105105
" @function(#SetWhetherToPerformIsAvailableChecksForTesting), skips the
106106
" IsAvailable check and always returns true.
107107
function! s:IsAvailable(formatter) abort
108-
if get(s:, 'check_formatters_available', 1)
108+
if codefmt#ShouldPerformIsAvailableChecks()
109109
return a:formatter.IsAvailable()
110110
endif
111111
return 1
@@ -253,6 +253,14 @@ function! codefmt#GetSupportedFormatters(ArgLead, CmdLine, CursorPos) abort
253253
endfunction
254254

255255

256+
""
257+
" @private
258+
" Returns whether to perform Availability checks, which is normall set for
259+
" testing. Defaults to 1 (enable availablity checks).
260+
function! codefmt#ShouldPerformIsAvailableChecks() abort
261+
return get(s:, 'check_formatters_available', 1)
262+
endfunction
263+
256264
""
257265
" @private
258266
" Configures whether codefmt should bypass FORMATTER.IsAvailable checks and

autoload/codefmt/clangformat.vim

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ let s:plugin = maktaba#plugin#Get('codefmt')
1919
function! s:ClangFormatHasAtLeastVersion(minimum_version) abort
2020
if !exists('s:clang_format_version')
2121
let l:executable = s:plugin.Flag('clang_format_executable')
22+
if codefmt#ShouldPerformIsAvailableChecks() && !executable(l:executable)
23+
return 0
24+
endif
25+
2226
let l:version_output =
2327
\ maktaba#syscall#Create([l:executable, '--version']).Call().stdout
2428
let l:version_string = matchstr(l:version_output, '\v\d+(.\d+)+')

autoload/codefmt/googlejava.vim

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
" Copyright 2017 Google Inc. All rights reserved.
2+
"
3+
" Licensed under the Apache License, Version 2.0 (the "License");
4+
" you may not use this file except in compliance with the License.
5+
" You may obtain a copy of the License at
6+
"
7+
" http://www.apache.org/licenses/LICENSE-2.0
8+
"
9+
" Unless required by applicable law or agreed to in writing, software
10+
" distributed under the License is distributed on an "AS IS" BASIS,
11+
" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
" See the License for the specific language governing permissions and
13+
" limitations under the License.
14+
15+
16+
let s:plugin = maktaba#plugin#Get('codefmt')
17+
18+
""
19+
" @private
20+
" Formatter: google-java-format
21+
function! codefmt#googlejava#GetFormatter() abort
22+
let l:formatter = {
23+
\ 'name': 'google-java-format',
24+
\ 'setup_instructions': 'Install google-java formatter ' .
25+
\ "(https://github.com/google/google-java-format). \n" .
26+
\ 'Enable with "Glaive codefmt google_java_executable=' .
27+
\ '"java -jar /path/to/google-java-format-VERSION-all-deps.jar" ' .
28+
\ 'in your vimrc' }
29+
30+
function l:formatter.IsAvailable() abort
31+
let l:exec = s:plugin.Flag('google_java_executable')
32+
if executable(l:exec)
33+
return 1
34+
elseif !empty(l:exec) && l:exec isnot# 'google-java-format'
35+
" The user has specified a custom formatter command. Hope it works.
36+
" /shrug.
37+
return 1
38+
else
39+
return 0
40+
endif
41+
endfunction
42+
43+
function l:formatter.AppliesToBuffer() abort
44+
return &filetype is# 'java'
45+
endfunction
46+
47+
""
48+
" Reformat the current buffer using java-format, only targeting {ranges}.
49+
function l:formatter.FormatRanges(ranges) abort
50+
if empty(a:ranges)
51+
return
52+
endif
53+
" Split the command on spaces, except when there's a proceeding \
54+
let l:cmd = split(s:plugin.Flag('google_java_executable'), '\\\@<! ')
55+
for [l:startline, l:endline] in a:ranges
56+
call maktaba#ensure#IsNumber(l:startline)
57+
call maktaba#ensure#IsNumber(l:endline)
58+
endfor
59+
let l:ranges_str = join(map(copy(a:ranges), 'v:val[0] . ":" . v:val[1]'), ',')
60+
let l:cmd += ['--lines', l:ranges_str, '-']
61+
62+
let l:input = join(getline(1, line('$')), "\n")
63+
let l:result = maktaba#syscall#Create(l:cmd).WithStdin(l:input).Call()
64+
let l:formatted = split(l:result.stdout, "\n")
65+
call maktaba#buffer#Overwrite(1, line('$'), l:formatted)
66+
endfunction
67+
68+
return l:formatter
69+
endfunction
70+
71+

instant/flags.vim

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,9 @@ call s:plugin.Flag('gn_executable', 'gn')
8787
""
8888
" The path to the buildifier executable.
8989
call s:plugin.Flag('buildifier_executable', 'buildifier')
90+
91+
""
92+
" The path to the google-java executable. Generally, this should have the
93+
" form:
94+
" `java -jar /path/to/google-java`
95+
call s:plugin.Flag('google_java_executable', 'google-java-format')

plugin/register.vim

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ call s:registry.AddExtension(codefmt#yapf#GetFormatter())
2929
call s:registry.AddExtension(codefmt#autopep8#GetFormatter())
3030
call s:registry.AddExtension(codefmt#gn#GetFormatter())
3131
call s:registry.AddExtension(codefmt#buildifier#GetFormatter())
32+
call s:registry.AddExtension(codefmt#googlejava#GetFormatter())

vroom/buildifier.vroom

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ examples.
1515
:call codefmt#SetWhetherToPerformIsAvailableChecksForTesting(0)
1616

1717

18-
The buildifer formatter expects the buildifier executable to be installed on
18+
The buildifier formatter expects the buildifier executable to be installed on
1919
your system.
2020

2121
% foo_library(name = "foo", srcs = ["bar.js"],)

vroom/clangformat.vroom

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ You can format any buffer with clang-format specifying the formatter explicitly.
7777

7878
Several filetypes will use the clang-format formatter by default: c, cpp,
7979
javascript, and proto. If the version of clang-format is >= 3.6, then it will
80-
also format java files.
80+
also format java files, but google-java-format is the default.
8181

8282
@clear
8383
% f();
@@ -101,7 +101,7 @@ also format java files.
101101
$ f();
102102

103103
:set filetype=java
104-
:FormatCode
104+
:FormatCode clang-format
105105
! clang-format .*
106106
$ { "Cursor": 0 }
107107
$ f();

vroom/googlejava.vroom

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
The built-in google-java formatter knows how to format Java BUILD files. If you
2+
aren't familiar with basic codefmt usage yet, see main.vroom first.
3+
4+
We'll set up codefmt and configure the vroom environment, then jump into some
5+
examples.
6+
7+
:source $VROOMDIR/setupvroom.vim
8+
9+
:let g:repeat_calls = []
10+
:function FakeRepeat(...)<CR>
11+
| call add(g:repeat_calls, a:000)<CR>
12+
:endfunction
13+
:call maktaba#test#Override('repeat#set', 'FakeRepeat')
14+
15+
:call codefmt#SetWhetherToPerformIsAvailableChecksForTesting(0)
16+
17+
18+
The google-java formatter expects a google-java executable to be installed on
19+
your system.
20+
21+
% class Foo { public String getFoo() { return "bar"; } }
22+
:FormatCode google-java-format
23+
! google-java-format .*
24+
$ class Foo {
25+
$ public String getFoo() {
26+
$ return "bar";
27+
$ }
28+
$ }
29+
30+
The name or path of the google-java executable can be configured via the
31+
google_java_executable flag if the default of "google-java" doesn't work.
32+
33+
:Glaive codefmt google_java_executable='java -jar /path/to/google-java.jar'
34+
:FormatCode google-java-format
35+
! java -jar /path/to/google-java.jar .*
36+
$ class Foo {
37+
$ public String getFoo() {
38+
$ return "bar";
39+
$ }
40+
$ }
41+
:Glaive codefmt google_java_executable='google-java-format'
42+
43+
The java filetype will use the clang formatter by default, so the default
44+
functionality is tested there.

vroom/jsbeautify.vroom

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,6 @@ javascript, json, html and css.
6161
@clear
6262
% f();
6363

64-
:set filetype=javascript
65-
:FormatCode
66-
! clang-format --version .*
67-
$ clang-format version 3.3.0 (tags/testing)
68-
! clang-format .*
69-
$ f();
70-
7164
:set filetype=json
7265
:FormatCode
7366
! js-beautify .*

0 commit comments

Comments
 (0)