3

At the moment I use prettier for formatting with vim (via Coc). The issue I have is that prettier is opinionated and, at the same time, inconsistent.

With javascript, functions look like this:


function cheese() {
  // stuff here
}

In PHP they look like this:


function cheese() 
{
  // stuff here
}

I want to be able to have full control over how conditionals, loops and functions look.

Is there a "vim way" of customising this?

I searched online but most solutions mention prettier!

1
  • Read the docs :h =.
    – 3N4N
    Oct 26, 2022 at 15:14

2 Answers 2

1

There are no builtin way to format code with Vim.

However Vim has two formatting commands:

  1. =
  2. gq

The first re-indent the content based on the file type.

The second reformat the content using either a VimScript or an external command.

How to associate an external command to a filetype is explained in the following answer: How to format code in vim using external commands

2
  • See in particular how you can customise Vim's internal 'cindent' indenting at :help cinoptions-values and the details of Vim's default PHP indenting at :help php-indent
    – Rich
    Oct 27, 2022 at 11:24
  • Also gw, and (as Rich points out) a massive number of options to control formatting and indenting behavior.
    – D. Ben Knoble
    Oct 28, 2022 at 13:55
2

As an alternative, use filters in your own command to call external tools. For example, for C and C++ you can run something like this:

" .vim/after/ftplugin/cpp.vim
command! -buffer Fmt let winsaved = winsaveview() | execute '%! clang-format --style WebKit' | if v:shell_error > 0 | silent undo | endif | call winrestview(winsaved)

The same idea is useful for pretty much any other language:

latex: %! latexindent

python: %! black - -q

go: %! gofmt

4
  • This is very similar to :setlocal formatprg=clang-format (latexindent/etc.), although you could reasonably choose indentprg, too.
    – D. Ben Knoble
    Oct 28, 2022 at 13:56
  • I don't think it is so reasonable to use indentprg for things that require more than indenting. You could use formatprg, but it becomes a big mess with complex logic and not so flexible as it cannot be used in autocommands, which is a common request for this sort of feature.
    – r_31415
    Oct 28, 2022 at 16:02
  • I don't follow "complex logic" or "cannot be used in autocommands," since formatprg only affects how the builtin gq works, which can be incorporated anywhere with :normal!
    – D. Ben Knoble
    Oct 28, 2022 at 17:56
  • Notice the additional commands to restore the view when malformed code triggers an error. For the record, I also use formatprg as you described for formatting visual selections.
    – r_31415
    Oct 28, 2022 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.