Friday, May 27, 2011

Re: formatprg and gq or gw

Reply to message «formatprg and gq or gw»,
sent 19:21:08 27 May 2011, Friday
by Kevin Walsh:

> Maybe formatexpr can help? Can I use formatexpr to invoke an external
> program but without the issues in 1 and 2?
Try
function s:Eval(expr)
return eval(a:expr)
endfunction
let s:sid=matchstr(s:Eval('expand("<sfile>")'), '\d\+')
function s:ParFormat()
let savedwinview=winsaveview()
try
execute v:lnum.','.(v:lnum+v:count-1).'!par -w'.&textwidth
finally
call winrestview(savedwinview)
endtry
endfunction
let &formatexpr='<SNR>'.s:sid.'_ParFormat()'

Original message:
> Hello,
>
> First time poster here, but long time vim user. Can someone help me
> with the formatprg variable?
>
> I set the variable to some external program, like:
> formatprg=par
>
> There are three problems I'd like help or advice on resolving:
>
> 1. gq} leaves the cursor on the last formatted line. This is sort of
> documented in the help, but it is also silly, and inconsistent with
> the behavior of gq} using the internal formatter. It seems that
> putting the cursor where the motion would have put it is much more
> reasonable, and this is what the happens with formatprg unset. It also
> allow "." to repeat the command for the next paragraph. Putting it on
> the last line of the paragraph seems pointless. Is there any way to
> work around this, so that the cursor is placed reasonably after
> invoking the external command?
>
> 2. Is there any way to send the external command the vim textwidth
> variable? I know I can do "formatprg=par\ -w80" or something, but I
> have different files with different textwidths. I was hoping for
> something like "formatprg=par\ -w$textwidth". Without this ability,
> the external formatprg is much less useful: it is both more powerful
> than the internal formatter, because it can invoke a program written
> in C or python or whatever, but also less powerful in that it can't
> even implement an equivalent to the standard internal formatter.
>
> 3. gq uses formatprg, but gw ignores it. This is documented. But is
> there some reason why this is so? It doesn't make any sense from the
> user perspective. Is a feature or just a documented bug?
>
> Maybe formatexpr can help? Can I use formatexpr to invoke an external
> program but without the issues in 1 and 2? And from reports on the
> web, it seems that gw might even use formatexpr, though the docs say
> otherwise. Does anyone have a simple example of a formatexpr I could
> modify for this purpose?
>
> Thanks,
> Kevin Walsh

No comments: