How can I script vim to run perltidy on a buffer?

后端 未结 6 1320
终归单人心
终归单人心 2021-02-02 00:42

At my current job, we have coding-style standards that are different from the ones I normally follow. Fortunately, we have a canned RC file for perltidy that I can

6条回答
  •  遥遥无期
    2021-02-02 01:03

    After trying @hobbs answer I noticed that when filtering the entire buffer through perltidy the cursor returned to byte 1, and I had to make a mental note of the original line number so I could go back after :Tidy completed.

    So building on @hobbs' and @Ignacio's answers, I added the following to my .vimrc:

    "define :Tidy command to run perltidy on visual selection || entire buffer"
    command -range=% -nargs=* Tidy ,!perltidy
    
    "run :Tidy on entire buffer and return cursor to (approximate) original position"
    fun DoTidy()
        let l = line(".")
        let c = col(".")
        :Tidy
        call cursor(l, c)
    endfun
    
    "shortcut for normal mode to run on entire buffer then return to current line"
    au Filetype perl nmap  :call DoTidy()
    
    "shortcut for visual mode to run on the current visual selection"
    au Filetype perl vmap  :Tidy
    

    (closing " added to comments for SO syntax highlighting purposes (not required, but valid vim syntax))

    DoTidy() will return the cursor to its original position plus or minus at most X bytes, where X is the number of bytes added/removed by perltidy relative to the original cursor position. But this is fairly trivial as long as you keep things tidy :).

    [Vim version: 7.2]

    EDIT: Updated DoTidy() to incorporate @mikew's comment for readability and for compatibility with Vim 7.0

提交回复
热议问题