Friday, April 2, 2021

Re: How to setup an external command to indent bash script?

On 2021-04-02, Peng Yu wrote:
> On 4/2/21, 'Grant Taylor' via vim_use <vim_use@googlegroups.com> wrote:
> > On 4/2/21 3:52 PM, Peng Yu wrote:
> >> I want to use shfmt to indent bash script in vim instead of using the
> >> default vim indenter. Could anybody show me how to set this up in vim?
> >
> > I would play with the formatprg setting.
> >
> > :help formatprg
> >
> >> shfmt -l -w script.sh
> >
> > Based on my read of the help section, it looks like formatprg expects to
> > read STDIN and write to STDOUT. So you might need some sort of wrapper
> > to read Vim's STDOUT to a file, shfmt said file, then write said file
> > back to Vim's STDIN.
>
> It can take the file from STDIN in this way. The output is to STDOUT.
>
> shfmt /dev/stdin < script.sh
>
> Could you show me the commands (that can be put in ~/.vimrc) to set
> formatprg to `shfmt /dev/stdin` just for a file when it is determined
> as a bash script? I don't want to mess it up for other file types.
>
> >
> > But I suspect that this is eminently doable.

Since you want to indent rather than format, a better choice of
options would be 'equalprg'. See

:help 'equalprg'

The 'equalprg' option is global or local to buffer, so you can set
it locally for the sh filetype and not have to worry about it
affecting other buffers.

You can enable it in your vimrc for sh and bash files like this:

au FileType sh setlocal equalprg=shfmt

Without any arguments, shfmt reads from stdin and writes to stdout,
just what you need here.

This won't automatically indent as you type--you'll have to execute
the = command on a range of lines. See

:help =

For Vim to format automatically as you type, you'd have to use
'indentexpr' and shfmt isn't intended to work in that context.

According to the shfmt project page, https://github.com/mvdan/sh,
someone has written a Vim plugin for shfmt,
https://github.com/z0mbix/vim-shfmt. You may want to check that
out, too.

Regards,
Gary

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20210402234124.GA28724%40phoenix.

No comments: