Skip to content

Add support for https://prettier.io #108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 15, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ helpfiles in the `doc/` directory. The helpfiles are also available via
* [GN](https://www.chromium.org/developers/gn-build-configuration) (gn)
* HTML (js-beautify)
* Java (google-java-format or clang-format)
* JavaScript (clang-format)
* JavaScript (clang-format or [prettier](https://prettier.io))
* JSON (js-beautify)
* Proto (clang-format)
* Python (Autopep8 or YAPF)
Expand Down
104 changes: 104 additions & 0 deletions autoload/codefmt/prettier.vim
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
" Copyright 2018 Google Inc. All rights reserved.
"
" Licensed under the Apache License, Version 2.0 (the "License");
" you may not use this file except in compliance with the License.
" You may obtain a copy of the License at
"
" http://www.apache.org/licenses/LICENSE-2.0
"
" Unless required by applicable law or agreed to in writing, software
" distributed under the License is distributed on an "AS IS" BASIS,
" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
" See the License for the specific language governing permissions and
" limitations under the License.


let s:plugin = maktaba#plugin#Get('codefmt')


""
" @private
" Formatter: prettier
function! codefmt#prettier#GetFormatter() abort
let l:formatter = {
\ 'name': 'prettier',
\ 'setup_instructions': 'Install prettier (https://prettier.io/) ' .
\ 'and configure the prettier_executable flag'}

function l:formatter.IsAvailable() abort
return executable(s:plugin.Flag('prettier_executable'))
endfunction

function l:formatter.AppliesToBuffer() abort
return &filetype is# 'javascript'
endfunction

""
" Reformat the current buffer with prettier or the binary named in
" @flag(prettier_executable), only targeting the range between {startline} and
" {endline}.
function l:formatter.FormatRange(startline, endline) abort
let l:Prettier_options = s:plugin.Flag('prettier_options')
if type(l:Prettier_options) is# type([])
let l:prettier_options = l:Prettier_options
elseif maktaba#value#IsCallable(l:Prettier_options)
let l:prettier_options = maktaba#function#Call(l:Prettier_options)
else
throw maktaba#error#WrongType(
\ 'prettier_options flag must be list or callable. Found %s',
\ string(l:Prettier_options))
endif
let l:cmd = [s:plugin.Flag('prettier_executable'), '--stdin', '--no-color']

" prettier is able to automatically choose the best parser if the filepath
" is provided. Otherwise, fall back to the previous default: babylon.
if @% == ""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment about what this part is doing?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

call extend(l:cmd, ['--parser', 'babylon'])
else
call extend(l:cmd, ['--stdin-filepath', @%])
endif

call maktaba#ensure#IsNumber(a:startline)
call maktaba#ensure#IsNumber(a:endline)

let l:lines = getline(1, line('$'))
let l:input = join(l:lines, "\n")
if a:startline > 1
let l:lines_start = join(l:lines[0 : a:startline - 1], "\n")
call extend(l:cmd, ['--range-start', string(strchars(l:lines_start))])
endif
let l:lines_end = join(l:lines[0 : a:endline - 1], "\n")
call extend(l:cmd, ['--range-end', string(strchars(l:lines_end))])

call extend(l:cmd, l:prettier_options)
try
let l:result = maktaba#syscall#Create(l:cmd).WithStdin(l:input).Call()
let l:formatted = split(l:result.stdout, "\n")
call maktaba#buffer#Overwrite(1, line('$'), l:formatted)
catch /ERROR(ShellError):/
" Parse all the errors and stick them in the quickfix list.
let l:errors = []
for l:line in split(v:exception, "\n")
let l:tokens = matchlist(l:line,
\ '\C\v^\[error\] stdin: (.*) \((\d+):(\d+)\).*')
if !empty(l:tokens)
call add(l:errors, {
\ 'filename': @%,
\ 'lnum': l:tokens[2],
\ 'col': l:tokens[3],
\ 'text': l:tokens[1]})
endif
endfor

if empty(l:errors)
" Couldn't parse prettier error format; display it all.
call maktaba#error#Shout('Error formatting file: %s', v:exception)
else
call setqflist(l:errors, 'r')
cc 1
endif
endtry
endfunction

return l:formatter
endfunction
30 changes: 30 additions & 0 deletions doc/codefmt.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,35 @@ Default: 'yapf' `
The path to the gn executable.
Default: 'gn' `

*codefmt:buildifier_executable*
The path to the buildifier executable.
Default: 'buildifier' `

*codefmt:google_java_executable*
The path to the google-java executable. Generally, this should have the form:
`java -jar /path/to/google-java`
Default: 'google-java-format' `

*codefmt:shfmt_options*
Command line arguments to to feed shfmt. Either a list or callable that takes
no args and returns a list with command line arguments. By default, uses the
Google's style. See https://github.com/mvdan/sh for details.
Default: ['-i', '2', '-sr', '-ci'] `

*codefmt:shfmt_executable*
The path to the shfmt executable.
Default: 'shfmt' `

*codefmt:prettier_options*
Command line arguments to to feed prettier. Either a list or callable that
takes no args and returns a list with command line arguments.
Default: [ '--single-quote', '--trailing-comma=all', '--arrow-parens=always',
'--print-width=80'] `

*codefmt:prettier_executable*
The path to the prettier executable.
Default: 'prettier' `

*codefmt:plugin[autocmds]*
Configures whether plugin/autocmds.vim should be loaded.
Default: 1 `
Expand Down Expand Up @@ -99,6 +128,7 @@ none is explicitly supplied via an explicit arg to |:FormatCode| or the
plugins are enabled or what other software is installed on your system.

The current list of defaults by filetype is:
* bzl (Bazel): buildifier
* c, cpp, proto, javascript, typescript: clang-format
* go: gofmt
* python: autopep8, yapf
Expand Down
11 changes: 11 additions & 0 deletions instant/flags.vim
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,14 @@ call s:plugin.Flag('shfmt_options', ['-i', '2', '-sr', '-ci'])
""
" The path to the shfmt executable.
call s:plugin.Flag('shfmt_executable', 'shfmt')

""
" Command line arguments to to feed prettier. Either a list or callable that
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to run vimdoc over the directory (see https://github.com/google/vimdoc) so the doc file picks up this edit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

" takes no args and returns a list with command line arguments.
call s:plugin.Flag('prettier_options', [
\ '--single-quote', '--trailing-comma=all',
\ '--arrow-parens=always', '--print-width=80'])

""
" The path to the prettier executable.
call s:plugin.Flag('prettier_executable', 'prettier')
3 changes: 3 additions & 0 deletions plugin/register.vim
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ endif
let s:registry = s:plugin.GetExtensionRegistry()
call s:registry.SetValidator('codefmt#EnsureFormatter')

" Formatters that are registered later are given more priority when deciding
" what the default formatter will be for a particular file type.
call s:registry.AddExtension(codefmt#jsbeautify#GetFormatter())
call s:registry.AddExtension(codefmt#prettier#GetFormatter())
call s:registry.AddExtension(codefmt#clangformat#GetFormatter())
call s:registry.AddExtension(codefmt#gofmt#GetFormatter())
call s:registry.AddExtension(codefmt#dartfmt#GetFormatter())
Expand Down
103 changes: 103 additions & 0 deletions vroom/prettier.vroom
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
The prettier formatter knows how to format JavaScript.
If you aren't familiar with basic codefmt usage yet, see main.vroom first.

We'll set up codefmt and configure the vroom environment, then jump into some
examples.

:source $VROOMDIR/setupvroom.vim

:let g:repeat_calls = []
:function FakeRepeat(...)<CR>
| call add(g:repeat_calls, a:000)<CR>
:endfunction
:call maktaba#test#Override('repeat#set', 'FakeRepeat')

:call codefmt#SetWhetherToPerformIsAvailableChecksForTesting(0)


The prettier formatter expects the prettier executable to be installed on your system.

% function HelloWorld(){if(!greeting){return null};}
:FormatCode prettier
! prettier .*
$ function HelloWorld() {
$ if (!greeting) {
$ return null;
$ }
$ }

The name or path of the prettier executable can be configured via the
prettier_executable flag if the default of "prettier" doesn't work.

:Glaive codefmt prettier_executable='myprettier'
:FormatCode prettier
! myprettier .*
$ function HelloWorld() {
$ if (!greeting) {
$ return null;
$ }
$ }
:Glaive codefmt prettier_executable='prettier'


You can format any buffer with prettier specifying the formatter explicitly.

@clear
% function HelloWorld(){if(!greeting){return null};}

:FormatCode prettier
! prettier .*2>.*
$ function HelloWorld() {
$ if (!greeting) {
$ return null;
$ }
$ }
function HelloWorld() {
if (!greeting) {
return null;
}
}
@end

Errors are reported using the quickfix list.

@clear
% function foo() {

:FormatCode prettier
! prettier .*2> (.*)
$ 2 (status)
$ echo >\1 ' (command)
|[error] stdin: SyntaxError: Unexpected token (2:1)\n
|[error] 1 | function foo() {\n
|[error] > 2 |\n
|[error] | ^'
function foo() {
@end
:echomsg line('.') . ',' . col('.')
~ 1,1
:echomsg string(map(getqflist(),
|'v:val.lnum . "," . v:val.col . "," . v:val.text'))
~ ['2,1,SyntaxError: Unexpected token']

It can format specific line ranges of code using :FormatLines.

@clear
% function HelloWorld(){if(!greeting){return null};}<CR>
|function Greet(){if(!greeting){return null};}

:1,1FormatLines prettier
! prettier .*--parser babylon --range-end 50.*2>.*
$ function HelloWorld() {
$ if (!greeting) {
$ return null;
$ }
$ }
$ function Greet(){if(!greeting){return null};}
function HelloWorld() {
if (!greeting) {
return null;
}
}
function Greet(){if(!greeting){return null};}
@end