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.
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
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!