6

I am figuring out a way to apply linting to a visual selection of code. For example:

enter image description here

I only want to lint run :ALEFix on that section of code, and not the 100s (or 1000s) of lines of other code in the file. My first thought was doing something like:

  • Copy the visual selection. y
  • Option a new file and paste that in. :vs tmp
  • Run :AleFix on that shortened file.
  • Copy-all: ggVG"*y
  • Close that file :q!
  • Do gv to re-highlight the visual selection at the start.
  • Paste in the copy-buffer p

What might be a better way to do that? And if the above seems like it might be the best way, what might be a clean function to do that with? (I'll try writing one myself as well...)

2 Answers 2

1

A little rough around the edges, but here is what I came up with (which I've tested and works for me):

function _AleVisualSelection()
    normal! gvy
    vs tmp
    normal!p
    ALEFix black
    normal! ggVG
    sleep 300m
endfunc

vnoremap    0   <Esc>:call _AleVisualSelection()<CR>y:q!<CR>gvp
1

You can use Vim's built-in :h formatprg and :h gq for this.

You can set formatprg option to the fixer/formatter tool of choice, like:

:let &l:formatprg='some-program --some-flag'

Or with set syntax which requires escaping spaces:

:setlocal formatprg=some-program\ --some-flag

You may persist this setting in your vimrc, like:

augroup RangeFixer
  autocmd!
  autocmd FileType python let &l:formatprg='some-program --some-flag'
augroup END

Or persist it in the appropriate ftplugin file (e.g. ~/.vim/ftplugin/python.vim or ~/.vim/after/ftplugin/python.vim), which removes the need for autocmds:

" ~/.vim/after/ftplugin/python.vim

let &l:formatprg='some-program --some-flag'

Once you have configured formatprg using one of above, then you can highlight the range you want to format, then press gq.

1
  • Or use gq<motion>/gq<text-object>
    – D. Ben Knoble
    Commented Jul 14, 2023 at 15:21

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.