One of the features of vim is it's ability to filter contents of the file through a command and return the output back to the buffer. This could be used for example for fixing the indentation on the file or generally formatting the document.
Part of the official documentation for the prettier/plugin-php is also this vimscript:
" Prettier for PHP
function PrettierPhpCursor()
let save_pos = getpos(".")
%! prettier --parser=php
call setpos('.', save_pos)
endfunction
" define custom command
command PrettierPhp call PrettierPhpCursor()
" format on save
autocmd BufwritePre *.php PrettierPhp
It uses a prettier
command available in PATH, install for instance via:
npm install -g prettier @prettier/plugin-php
The script works as advertised, the PHP file is formatted on save, depending on prettier settings, it could look similar to this:
The excessive spaces get removed, the missing ones are introduced and the quoting is made consistent, among others formatting tasks it handles. Nice.
The problem
But this fairytale situation is more dire, if the PHP code contains a syntax error or a similar problem:
Not only one is distracted with the shell returned 2
message but also
Type ENTER or type command to continue, which replaces the contents of
the current buffer with the error message.
This can be undone by pressing u
but then the cursor position on the top
of the file. Getting cursor back where it was are even more unnecessary
keystrokes.
The solution
By tweaking the mentioned vimscript a little, I was able to get a more pleasurable solution out of the setup:
" Prettier for PHP
function PrettierPhpCursor()
let save_pos = getpos(".")
%! prettier --parser=php
" undo automatically on error
if v:shell_error | silent undo | endif
call setpos('.', save_pos)
endfunction
" define custom command
command PrettierPhp call PrettierPhpCursor()
" format on save silently
autocmd BufwritePre *.php silent PrettierPhp
Also, prettier command has numerous options to set, either via
.prettierrc
file or right in the vimscript like:
%! prettier --parser=php --brace-style=1tbs
More details can be found in the Configuration section of the documentation or via:
npx prettier --parser=php --help
It looks like modified vimscript is working without much disruptions now. Enjoy!
Links
- https://github.com/prettier/plugin-php
- https://askubuntu.com/a/719000/350681
- https://vimhelp.org/cmdline.txt.html#%3A%25
- https://vimhelp.org/various.txt.html#%3A%21
- https://stackoverflow.com/a/6074494/1972509
- https://stackoverflow.com/a/62976064/1972509
- https://stackoverflow.com/questions/26051680/display-stdout-in-vim-when-external-command-fails
- https://vi.stackexchange.com/questions/5795/shell-returned-2-when-i-try-to-indent
- https://vi.stackexchange.com/questions/7116/how-can-i-filter-a-buffer-to-an-external-command-on-save-without-causing-any-sid/7118
- https://stackoverflow.com/questions/11703174/abort-write-in-bufwritepre-of-vim-script