1

Is there a way to bind a single in visual mode, or a small word in ex mode that will invoke the code formatter for the active filetype? For example "ESC : fmt" or CTRL ALT F in visual mode, to invoke "ESC : Prettier" or "ESC : RustFmt" for javascript or rust code respectively.

2

You are looking for :h 'formatprg':

'formatprg' 'fp'    string (default "")
            global or local to buffer |global-local|
    The name of an external program that will be used to format the lines
    selected with the |gq| operator.  The program must take the input on
    stdin and produce the output on stdout.  The Unix program "fmt" is
    such a program.
    If the 'formatexpr' option is not empty it will be used instead.
    Otherwise, if 'formatprg' option is an empty string, the internal
    format function will be used |C-indenting|.

You can set it to use an external formatting tool or the built-in mechanism.

Once you have set formatprg properly you can use gq as a command to format your code the same way you'd use d to delete it or y to yank it. For example gqip will format the current paragraph.

You can also use :h 'equalprg' and the command =.

And as you want to have a different setting for each filetype, the best practice is to set it in a ftplugin

For example for javascript you could create a file ~/.vim/after/ftplugin/javascript.vim and put something like the following in it:

setlocal formatprg=prettier\ --stdin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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