Start Selection After Cursor in ViEmu Visual Mode - vim

Ok, this was previously a question about Vim until I learned it was particular to the Visual Studio plugin ViEmu.
In ViEmu, 'v' puts the highlighter cursor between the previous character and the current one, such that walking backward leaves the letter that was under cursor when 'v' was pushed unselected. This is particularly annoying when trying to use visual mode from the end of the line. Is there a key that is to 'v' as 'a' vs. 'i' and 'p' vs 'P'.
Here's an example:
I have the following text with my cursor sitting over the trailing s of the word dances.
The fat yellow dog dances
and I wish to to change it to:
The quick brown fox jumps
I'd like to enter visual mode with the highlighter positioned to the right of the s in dances. That way, as I use shift+f to search backward to say the f in fat I select everything. Using v->shift+f->f will highlight everything but the s in dances which is annoying.

If we think about how a change made with an operator, say d3e, is different from the same change made using Visual mode, v3ed, we find that the distinctive element in Visual mode is that of interactivity.
In Visual mode it is natural to start selecting and then steadily honing in on the target area: Instead of v3ed I might as well use veeed or veeeebbed or v4ebbed. Or maybe after vee I realise I need to include stuff that comes before my selection, thus o, bb, and finally d.
The point is, when using
operators, we need to be precise: operator plus target – a hole-in-one shot;
Visual mode, we are free to employ the full array of Vim's motions to describe our target area, whatever shape it may be, and there's no pressure to be precise or hit the mark immediately.
In case you often need to start Visual mode just after the current cursor position (or you have another similar use case), you can always create a custom mapping. Here are some ideas:
:nnoremap <Leader>v <Space>v
:nnoremap <Leader>v $hv
:nnoremap <Leader>v $F;v

Related

How to efficiently add parentheses or a string in vim?

In traditional text editors, whenever I needed to open a string or parentheses and type something between it I used to do:
Type () or ""
Press left
Type in what I need
Press right
But in vim (that is if I followed the vim way) the process becomes quite tedious as I have to enter the normal mode to move a whole bunch of times:
Type () or ""
Press <ESC>
Press i
Type what I need
Press <ESC>
Press l
Press a
If it is not a good practice to use the arrow keys at any time, is there a more efficient way of doing this kind of task in vim?
It is actually quite easy to automatically append those closing characters in a mapping, and put your cursor where you want it. The trick is to do that, without also messing up the undo/redo/repeat actions. The problem is that cursor movement commands in insert mode will break the "undo sequence" so that any change you make after moving the cursor is undone separately from changes made before moving the cursor.
Warning: the following information may become dated
There are plenty of plugins available to automatically append these characters (see the partial list at the Vim wiki page for appending closing characters), and prior to Vim 7.4, some of them even had complicated workarounds for keeping the undo sequence intact. Unfortunately, they all relied on a bug in Vim that got fixed in version 7.4 for this.
A patch is available to add a cursor movement that does not break undo, so if you want to compile Vim yourself, you can grab that patch and use mappings like the following (no plugin required!) to do what you want:
inoremap ( ()<C-G>U<Left>
inoremap <expr> ) strpart(getline('.'), col('.')-1, 1) == ")" ? "\<C-G>U\<Right>" : ")"
These mappings will insert "()" when you type an opening (, placing the cursor in between the parentheses. When you type ')' and there is already a closing ')' after the cursor, Vim will skip over the parenthesis instead of inserting a new one. Cursor movement is preceded by <C-G>U which is the feature the aforementioned patch adds, allowing the following cursor movement to not break the undo sequence (as long as the movement is all in a single line).
As of Vim 7.4.663, this patch has still not been officially included.
No. Doing it in Vim is exactly the same as in your "traditional" editor:
Type () or ""
Press left
Type in what you need
Press right
But… why don't you type the opening character, what you want inside the pair and then the closing character?
Type ( or "
Type what you need
Type ) or "
Too simple?
I think using arrow keys to move around is bad practice in normal mode but in your case; moving one space while in insert mode, I would hazard to say using the arrow keys is probably best practice.
That being said if you are dead set on avoiding them you could use <i_ctrl-o>.
:help i_ctrl_o
CTRL-O execute one command, return to Insert mode *i_CTRL-O*
So, while in insert mode, you could type: ()<ctrl-o>h<xxx><ctrl-o>l, where <xxx> is whatever you want in the brackets.
Unfortunately that doesn't work if you cursor is on the last character of the line, which if you are typing it most likely is.
To solve that problem do :set virtualedit+=onemore or add it to your ~/.vimrc file.
Note that this solution is more keystrokes than simply using the arrow keys but you don't need to move your hands away from the home row so it may be faster anyway.

Vim: How to shrink the visual area

Let's say that I've got the following text:
This allows you to select some text using Vim's visual mode
With the cursor on the 'a' in 'allows'. If I type vaw I switch to visual mode and then select "a word" ("allows "). If I repeat the aw then Vim also selects the "you ". Let's say I do this once more (highlighting "to ") and then realize that I've gone too far.
Is there a way to shrink/reduce the size of the visual area (other than using the h,j,k,l keys)?
I'd love to be able to either 'undo' my last command (i.e., have Vim move the selection back to before I typed that last 'aw') or else use the motion/text object commands to reduce the size of the visual area.
yes, you can keep pressing ge till it selecting allows again.
Based on your post (and on this one), I decided to make the vim-visual-history plugin that keeps
a traversable record of previous visual selections with [v, ]v, [V and ]V. So
in your case, you would just do [v to go back one selection. You can keep on pressing [v to go back further in time, and use ]v to go forwards again. The plugin works for your case, and also selections using text objects etc.
[count][v : Reselect previous visual selection
[count]]v : Reselect next visual selection
[V : Reselect first visual selection
]V : Reselect last visual selection
You can also give a count to jump through the history faster:

How to jump to the start or the end of visual selection in Vim?

Is there a motion for moving to the start or end of a visual selection?
I know that o while in visual mode alternates between the two, but I need to be able to select precisely the start.
The overall goal is to surround a visually selected area with parentheses.
Follow-Up:
Based on the comments, I was able to implement this using the following macro. The idea is to:
Esc to exit visual mode;
`> to go to the end of the previous visual selection;
a) to append a closing parentheses;
Esc to exit insert mode;
`< to go to the start of the previous visual selection;
i( to insert an opening parentheses;
Esc to exit insert mode again.
For example:
map \q <ESC>`>a)<ESC>`<i(<ESC>
Based on another comment, we have an even more concise solution:
map \q c()<ESC>P
There are two relevant built-in marks holding the positions of the first
and last characters of the last visual selection in the current buffer.
In order to move the cursor to these marks, use the commands `<
and `>, respectively (see :help `> and :help `<).
While you are in Visual Selection click o. It will change position of cursor to other end of selection. Then O to jump back.
The easiest way to "surround a visually selected area with parentheses" is:
change the visually selected area to () and Put it back in the middle: c()<ESC>P
I suggest defining in the .vimrc file a new visual-mode command (e.g., \q) with that:
:vmap \q c()<ESC>P
This approach also works with visual rectangular areas (<C-V>): it
puts ( and ) around each block-line.
if you just want to surround a visual selection there has already work been done, namely by tim pope, who wrote this plugin called surround. It surrounds words or visual selection with delimiters of your liking.
select your visual selection, say i like vim hit S) to get (i like vim) or S( to get ( i like vim ), to change this to [i like vim] type cs] (change surrounding) and to delete ds] to get i like vim at last.
If you can't use Surrond.vim, here is one way to do it:
Do your visual selection with v or V.
Get out of it with <Esc>.
Type `>a)<Esc> to insert a closing parenthesis after the last character of the selection.
Type `<i(<Esc> to insert an open parenthesis before the first character of the selection.

When is Visual mode used in Vim?

I'm relatively new to the world of Vim. I've been learning my way around it but have yet to find a practical purpose to enter visual mode.
What are some scenarios when visual mode is especially useful?
Are there actions that can only be performed from within visual mode?
I use visual mode when I want to highlight a section of text. I start by typing v in standard mode, which then enables the visual mode. Then I use the arrow keys to move the cursor. This causes the text between my starting point and the current cursor location to be highlighted. Once you select a section of text like this, entering a command (e.g. search/replace) in command mode (by typing :) will only affect the selected area.
Another useful visual command is shift+v (visual line). This does the same as above, but it selects entire lines at a time instead of individual characters.
When you want to comment a block of text.
In command mode :
Shift + v
,ctrl +v,
j or k,
I , #(comment
character) and then Esc
Vim inserts the comment character to
the start of the block..
is when I am using Gvim, I find it much easier to copy data
to the clipboard through visual mode.
In command mode :
Shift + v
, j or k ,
" , +
,y
Here + is the clipboard
register
This to me is much more legible that using markers
is for manual indenting
Shift + v,
Shift + > for
moving to the right.
Shift + < for
moving to the left. .
repeats
this is fun :-)
One of the nice things about visual mode is that, because of Vim's focus on modality, you can perform most of the commands that you are used to (such as search/replace with :s, d to delete text, or r to replace text) while also seeing exactly what will be affected -- this allows you to determine the exact scope of whatever you are doing.
Furthermore, as someone else mentioned, you can easily insert a prefix (like a comment character or, say, & for alignment or \item in LaTeX) by selecting the first character of each line in visual block mode (ctrl+v), pressing I to insert before the first character, typing in whatever you want to insert, and then Escing back to normal mode.
The last kind of visual mode is visual line (Shift+v), which allows you to quickly select a number of lines. From there, you can change their indentation using > or < (prefix this with a number to indent by that many tabs), use d or y to delete or copy those lines, use zf to create a new fold from those lines, or use any other selection-based command.
Finally, there are a lot of other cool things you can do with visual mode, including gv to reselect your last visual[line/block] mode selection, gU to convert a visual selection to uppercase or gu for lowercase, and many more.
In addition to the other (great) answers, it's an easy way to define scope for an action. For example, to limit a search & replace to a specific method...
Say you have this code:
function foo() {
abc();
while (1) {
def();
abc();
}
}
You can place the cursor on any of the braces or parentheses and press v, %, :, s/abc/xyz/g and your search & replace will have a defined scope in which the action will occur.
Visual mode is useful if you want to apply a command to a section of text that isn't easily described as a primitive movement command. You can select some text in visual mode with a complex sequence of movements and then apply a command to that selection.
I often find myself using visual-block mode (Ctrl + v) more than any of the other visual modes.
You can easily remove indentation, comments, etc. once you are aware of this mode. In my experience, this is often faster than figuring out how to form an equivalent search-and-delete statement.
You can also add indentation (or comments as Cherian stated) by selecting a block of text and pressing I, typing whatever you want to add, and pressing Esc (note: you may need to redraw the screen (e.g. by moving the cursor) to see the effects of this).
I haven't seen the following mentioned, probably because they're subtle.
1 - Less hassle with the unnamed register
Whenever you copy (yank) some text, and then want to d to change some other text, e.g., diw to "delete inner word," Vim will place the deleted text into the unnamed register. Then if you try to paste, it will just paste the deleted text right back unless you do "0p to paste from the 0 register.
But with visual mode, you can just do something like viwp and don't have to mess with registers.
So, for comparison, to copy and replace inside some parens:
yiw -> move somewhere -> vi(p
vs
yiw -> move -> ci(<C-r>0p
yiw -> move -> "_di(p
yiw -> move -> di("0P
Note: this also works for deleting text and pasting it back over a text object. See here.
2 - Jumping to parts of a text object
If you want to jump to the beginning or end of a text object, you can select it in visual mode and press o. For example, va" to select anywhere inside quotes, and then press o to jump to the matching quotes, kind of like % for matching brackets.

Is there a way to emulate ReSharper's "extend selection" feature in Vim?

ReSharper has a nice feature called "extend selection": by pressing CTRL+W (I think this is the default) repeatedly, you select more and more from your current caret location. First it's a word, then more and more words, a line, inner then outer block of lines (for example an if-block), then a function, etc...
Basically, by pressing the key combination repeatedly, you can end up selecting the entire file. I'm sure at least some of you will be familiar with it.
I have just started learning all the intricacies of vim and I don't have enough experience to see how something like this could be implemented in Vim (although I assume it's possible). So my question is meant for Vim gurus out there: can this be done and how?
Update: a bit of a background story. I've been talking to my ex-boss about all the benefits of Vim, and he thinks it's all great. His only question/problem was: does it have "extend selection"? My question so far has been no. So, if someone knows the answer, I'll finally win a discussion :P (and maybe create a new Vim convert:-))
I had a quick go at this problem. It doesn't work as is. Feel Free to make edits and post on the vim wiki or as a plugin if you get it refined.
chances are you'd want to make a g:resharp_list for each language (eg. one for paranthesised languages, etc.)
All that is needed is a marker for the original cursor position :he markers and a timeout autocommand that resets the index.
"resharp emulator
"TODO this needs a marker
"also c-w is bad mapping as it has a lag with all the other-
"window mappings
"
let g:resharp_index = 0
let g:resharp_select = ['iw', 'is', 'ip', 'ggVG']
func! ResharpSelect()
if g:resharp_index >= len (g:resharp_select)
let g:resharp_index = 0
endif
exe "norm \<esc>v" . g:resharp_select[g:resharp_index]
let g:resharp_index = g:resharp_index + 1
endfun
nnoremap <c-w> :call ResharpSelect()<cr>
vnoremap <c-w> :call ResharpSelect()<cr>
"Something to reset on timeout. TODO this doesn't work
au CursorHold :let g:resharp_index = 0<cr>
The answer is yes. Once in Visual mode you can use all the regular navigation methods as well as some extra ones.
Some of my favourites? First hit v while in normal mode to get to visual mode then hit:
iw - to select the inner word. Great for selecting a word while excluding surrounding braces or quotes
w - hit multiple times to keep selecting each subsequent word.
b - select wordwise backwords
^ - select all from current position to beginning of text on line
$ - select all from current position to end of line
I'm sure others here could add to this list as well. Oh and don't forget Visual Block mode C-v try it out in vim with the above commands it works in two dimensions :-)
If you're talking about Vim (and you should be :-), you can start marking text with the v command, then you have all the standard cursor movement commands (and, as you know, there are a lot of them) which will extend the selection, as well as moving the cursor.
Then you just do whatever you want with the selected text.
See here for the gory details.
One would need to write a function that would save the current selection, then try increasingly wide selections, until the new selection exceeds the saved one or selects all text. Some possible selections are:
viW - select word
vis - select sentence
vip - select paragraph
viB - select text within the innermost brackets
v2iB - select text within the next most innermost brackets
ggVG - select all text
I think Jeremy Wall's heading in the right direction. And to get a little further in that direction, you might look at the "surround.vim" script from Tim Pope. A good description is available on github. Or, if you'd rather, get it from vim.org. It'll probably help you do some of the things you'd like to do, though it doesn't seem to have a feature for say, simply selecting within a tag. Let me know if I'm wrong.
Ultimately, what you'd really like is a hierarchy of enclosing text-objects. You should read up on text-objects if you haven't. A nice overview is here. Note that you can grab multiple objects in one go using counts, or do this iteratively (try vawasap}}} from normal mode).
You can also get scripts which define other text-objects, like this one that uses indentation to define a text-object. It'll work for many languages if you're formatting according to common standards, and guaranteed for python.
One annoyance is that the cursor ends up at the end of the visual block, so, for example, you can't easily select everything between some ()'s, then get the function name that precedes them...
...BUT, I just found in this post that you can change this behavior with o. Cool!
I suspect you'll find yourself more efficient being able to skip over intermediate selections in the long run.
Anyway, I'll be curious to see if anyone else comes up with a more general solution as well!
In Rider [on a Mac with VS Mac bindings with IdeaVim], I bind:
Ctrl+= to Extend Selection
Ctrl+- to Shrink Selection
Doesn't clash with any other bindings of consequence and doesn't require a v for mode switching, and easier than Cmd+Option+-> and Cmd+Option+<-
Putting it here as I always hit this question with any Rider Vim selection searches. If I get enough harassment, I'll create a self-answered "How to use Extend Selection with Rider Vim mode".

Resources