How do I prevent auto visual mode exit after an action?

I want to prevent exitting visual mode especially when I have selected a visual block and pasted it somewhere. An example use case is: I copy and paste a block of code between two files, but then I want to fix the indentation after pasting. I don't want to reselect the block of code once again and then fix the indentation.


Solution 1:

I want to prevent exitting visual mode

You can't. After executing a command in visual mode you have to leave it for normal mode.

I don't want to reselect the block of code once again

An example use case is: I copy and paste a block of code

In your case it's a new block, so it cannot be "re-selected". So you really have to select it yourself. Use 1v (or 1vl if set selection=exclusive) to simplify this operation.

Also you can always create a mapping. For example

nnoremap <Leader>p pg`[1v

Solution 2:

Actually you can use gv option to "re-select" the previously selected visual block. I actually use the following options to stay in visual mode after indenting a block.

vnoremap < < gv
vnoremap > > gv

Basically, it is a mapping in visual mode with no recursive maping (vnoremap) that maps the < command to < gv. In other words, it applies < and gv afterwards. Hence, you can take action and "re-select" the previously selected visual block.

Edit: And here is another example that maps Alt+k and Alt+j to move selected visual block up and down, while "re-select"ing the visual block.

vnoremap <A-k> :m '<-2<CR>gv=gv
vnoremap <A-j> :m '>+1<CR>gv=gv