Format All on Save Coc-Prettier

Viewed 6657

I am new to Vim and using coc-prettier to format my files. I can use the command :Prettier to format my files, but want to do it automatically for ALL file types. I found this, but I need to specify the file types:

"coc.preferences.formatOnSaveFiletypes": ["css", "markdown"],

I want it to auto format on save for all. How can I do this? Thanks!

5 Answers

Apparently formatting on all file types on save is possible as of the commit #1150

Seems to work for me.

The exact implementation:

"coc.preferences.formatOnSaveFiletypes":  ["*"]

Taking a look at the schema.json:

"formatterPriority": {
      "type": "number",
      "default": 0,
      "description": "Priority of this languageserver's fomatter."

also referenced in the coc-prettier GitHub - here:

prettier.formatterPriority (default: 1) - priority of fomatter

Change it to -1 if you don't want prettier to have higher priority than formatter provided by other language server.

Generally speaking coc-prettier uses prettier which on the other hand makes usage of ESLint. Therefore (also for future problems), I'd suggest expanding your search term to broaden up the results. Anyhow, don't forget to properly declare the priority in the configuration file - as mentioned above in the linked documentation.


A little edit regarding a discussion between me and the bounty awarder @DanMacák:

Hence I wanted to find out if something like "coc.preferences.formatOnSaveFiletypes": '*' is possible. Which I checked the schema for back then and found that this option is not viable.

After doing some further research on the added question, I found out that it isn't possible (at least to my knowledge). coc.preferences.formatOnSaveFiletypes only takes an array as an input - see below:

"coc.preferences.formatOnSaveFiletypes": {
      "type": "array",
      "default": [],
      "description": "Filetypes that should run format on save.",
      "items": {
        "type": "string"
      }

Unless there is a way to include every element into an array, via e.g. the asterisk operator, chances are slim you can parse said information into the function. Or to sum things up, the functionality is unfortunately not provided the way you intend to use it.

Set coc.preferences.formatOnSaveFiletypesto ["*"] to enable format on all filetypes.

Vim has excellent built in formatting. So you can leverage that to do the formatting for you. Add this to your ~/.vimrc to autoformat the file on save.

autocmd BufWritePost * execute "normal gg=G"

Add the configs you require like tabstop and shiftwidth to format as you require it.

Related