When is Visual mode used in Vim? - 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.

Related

How to execute specific regex substitution on selected lines in visual mode in vim

I want to replicate the VS code feature of 'highlight and comment out code' (usually bound to keys SHIFT + /) in vim.
I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line. I just want to put a constraint on this so it only applies the substitution to lines highlighted in visual mode.
Visually select all the lines (using V), then hit :.
This will give you :'<,'> which is the range of your visual selection.
Then you can add your vim command to it.
I would recommend the following method if you wish to not use plugins.
:'<,'>normal I//
Which is not a substitution.
If you want a really nice vim plugin that does this task in a vim manner, check out tpope's vim-commentary which is an essential in my opinion.
I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line.
Well, that would be an unnecessarily complicated way to do it and your command wouldn't really work anyway.
:g// either matches nothing or it matches the previous search. What you want, here, is probably something like :g/^/ or :g/$/.
A simple substitution on the whole buffer would be much simpler and much faster:
:%s/^/\/\/ /
Using :help :global in this context provides no value (you want to operate on every line anyway) and is considerably slower (we are talking thousands of times slower)
You can use alternative separators to avoid all that backslashing:
:%s#^#// #
The last separator is not even needed:
:%s#^#// <-- there is a space, here
And the kicker: you can enter command-line mode from visual mode like you would do from normal mode, by pressing :. So you can simply make your visual selection, press :, and run your substitution:
v " enter visual mode
<motion> " expand the selection
: " press :
:'<,'> " Vim inserts the range covering the visual selection for you
:'<,'>s#^#// <CR> " perform your substitution

What is the difference between s, c and r commands in vi/vim?

I am trying to clarify this from the OReilly book on Vim, but the examples presented aren't clear enough.
Clarification via examples/use-cases instead of direct explanation would be very helpful.
The Sample text could be:
With a
screen editor,
you can
scroll the page, move the cursor.
Assume you have foo in the document, and the cursor is on the f.
Now, pressing rb will change this to boo, and you are back in command mode. Pressing sb will accomplish the same, but you are in insert mode and can insert more characters. Finally, c requires some kind of motion; e.g. you can type cw to remove the whole word and enter insert mode. On the other hand, cl is essentially the same as s.
Descriptions
s (substitute) will delete the current character and place the user in insert mode with the cursor between the two surrounding characters. 3s, for example, will delete the next three characters and place the user in insert mode.
c (change) takes a vi/vim motion (such as w, j, b, etc.). It deletes the characters from the current cursor position up to the end of the movement. Note that this means that s is equivalent to cl (vim documentation itself claims these are synonyms).
r (replace) never enters insert mode at all. Instead, it expects another character, which it will then use to replace the character currently under the cursor.
Examples
Take your sample text, and image the cursor at the beginning of the word 'can' (line 3).
Typing spl<Esc> in vi/vim.
Here, we have s for substitute. pl is the text to insert, and <Esc> will exit insert mode. Put together, it will change can to plan like this:
With a
screen editor,
you plan
scroll the page, move the cursor.
Typing cwcould<Esc> in vi/vim.
c is for change, and w tells c to delete through the next word, can. Next we type the text for insert mode, could. Lastly, we need to type <Esc> again to exit insert mode. The command will change can to could like this:
With a
screen editor,
you could
scroll the page, move the cursor.
Typing rf in vi/vim.
Here we type r for replace, then f as the new character which r uses to replace the original character with. This changes can to fan like this:
With a
screen editor,
you fan
scroll the page, move the cursor.
Notes
There's a lot of hidden uses to the simple commands in vi/vim that highlight more differences between these commands. Since I almost always use vim over vi, these features might be vim-exclusive, I'm not certain.
Maximizing the utility of commands like c, y, and d that take motions requires having a good grasp of text-objects (type help text-objects in vim. These aren't in vi.)
Because r takes a character instead of entering insert mode, you can input characters that would otherwise be difficult to add in. Typing r<C-R> (that's r, then ctrl-r) replaces the current character with a ctrl-r character. This might be surprising since pressing ctrl-r in insert mode awaits another key that is the register to paste.
All three of these commands can be repeated with the . command, substituting, changing, or replacing the same region relative to the cursor with the given text.
When typing a number n before the command, s and c delete n items (characters for s, or movements for c), and then inserts text once. Using a number n before r, however, replaces the next n characters with that many copies of the chosen character. For example, 4r0 could replace 1234 with 0000 all at once.
:help c
:help s
:help r
Easy.
Instead of wasting your time on that book, learn how to use Vim's awesome internal documentation:
:h s
:h :command
:h 'option'
:h function()
:h ctrl-x
:h i_ctrl-x
:h subject
:h foo<Tab>
:helpgrep foo
You may try these commands in visual block mode (press <C-v> to enter), they act a little different.
When you select a block of characters and then type s, it will immediately remove the block and enter insert mode, whatever you input next will be inserted in the same position on each of the lines affected by the visual block selection.
Command c basically does the same thing.
What interesting is command r, when you type ra after you select a block, it will replace every character in that block to a instead of just leave one column of a. I think this can be very useful at some point.

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.

vim search pattern for a piece of text line yanked in visual mode

I am trying search a part of some line which is yanked under visual mode.
What's the quickest way to do it in VIM? For exmaple,
Hello, #{1} world.
I press v enter visual mode and select llo, #{1} wor at the line 1. Then I yanked the selected text by pressing y, and then, I am trying to search for the selected text by pressing /. That leads to the following questions:
A: How to past a yanked text when I am in search mode?
B: How to avoid the work of escaping characters for a search pattern?
A:
Ctrl-r 0.
B:
In addition to the Ctrl-r 0 trick, there's also Ctrl-r =, which lets you type in an expression to be evaluated and expands to the result.
/ (now the prompt looks like /)
Ctrl-R = (now the prompt looks like =)
escape(#0, '\^$*.~[') Enter (now the prompt looks like /llo, #{1} wor)
Enter
Note that #reg means "the contents of register reg", and register 0 is the the last yank or delete. I think that escapes all the characters which are special in vi regexps… in any case, you would probably prefer to make a mapping than to type that all in.
When you yank some text (and specify no register to yank it into), it goes to register 0. So, if you want to search for that yanked text, press ESC to get into normal mode and then
/CTRL-r0
(i.e. press /, then CTRL+r, then 0) to pull the content of register 0 into the search pattern.
Some notes:
To search for other patterns stored in other registers, you could type :reg and watch the register contents before deciding which register content to use for your search.
To yank into a different register than 0 (e.g. 2), you could type "2y (:he v_y).
To search for the selected text directly, you could use the mapping described here which enables you to simply press X (uppercase character X) while in visual mode to search for that text.
For searching in general, this vimcast gives you an introduction to the very powerful command line window with the history of searches (discovered it two weeks ago and absolutely love it!).
I've overriden the star command for the visual mode (NB: it requires one file from lh-vim-lib). It answers your need:
select in visual mode
press */#
continue searching with n/N

Simple Vim commands you wish you'd known earlier [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm learning new commands in Vim all the time, but I'm sure everyone learns something new once in a while. I just recently learned about this:
zz, zt, zb - position cursor at middle, top, or bottom of screen
What are some other useful or elegant commands you wish you'd learned ages ago?
I really wish I'd known that you can use Ctrl+C instead of Esc to switch out of insert mode. That's been a real productivity boost for me.
The most recent "wow" trick that I learnt is a method of doing complicated search-and-replace. Quite often in the past, I've had a really complicated regexp to do substitutions on and it's not worked. There is a better way:
:set incsearch " I have this in .vimrc
/my complicated regexp " Highlighted as you enter characters
:%s//replace with this/ " You don't have to type it again
The "trick" here (for want of a better word) is the way that you can use the search to create the regexp (and 'incsearch' highlights it as you enter characters) and then use an empty pattern in the substitution: the empty pattern defaults to the last search pattern.
Example:
/blue\(\d\+\)
:%s//red\1/
Equivalent to:
:%s/blue\(\d\+\)/red\1/
See:
:help 'incsearch'
:help :substitute
I created this reference of my most used command for a friend of mine:
select v
select row(s) SHIFT + v
select blocks (columns) CTRL + v
indent selected text >
unindent selected text <
list buffers :ls
open buffer :bN (N = buffer number)
print :hardcopy
open a file :e /path/to/file.txt
:e C:\Path\To\File.txt
sort selected rows :sort
search for word under cursor *
open file under cursor gf
(absolute path or relative)
format selected code =
select contents of entire file ggVG
convert selected text to uppercase U
convert selected text to lowercase u
invert case of selected text ~
convert tabs to spaces :retab
start recording a macro qX (X = key to assign macro to)
stop recording a macro q
playback macro #X (X = key macro was assigned to)
replay previously played macro * ##
auto-complete a word you are typing ** CTRL + n
bookmark current place in file mX (X = key to assign bookmark to)
jump to bookmark `X (X = key bookmark was assigned to
` = back tick/tilde key)
show all bookmarks :marks
delete a bookmark :delm X (X = key bookmark to delete)
delete all bookmarks :delm!
split screen horizontally :split
split screen vertically :vsplit
navigating split screens CTRL + w + j = move down a screen
CTRL + w + k = move up a screen
CTRL + w + h = move left a screen
CTRL + w + l = move right a screen
close all other split screens :only
* - As with other commands in vi, you can playback a macro any number of times.
The following command would playback the macro assigned to the key `w' 100
times: 100#w
** - Vim uses words that exist in your current buffer and any other buffer you may have open for auto-complete suggestions.
gi switches to insertion mode, placing the cursor at the same location it was previously.
:q!
I wish I knew that before I started vi for the first time.
^X-F completes using filenames from the current directory. No more copying/pasting from the terminal or painful double checking.
^X-P completes using words in the current file
:set scrollbind forces one buffer to scroll alongside another. e.g. split your window into two vertical panes. Load one file in each (perhaps different versions of the same file). Do :set scrollbind in each. Now when you scroll in one, both panes will scroll together. Ideal for comparing files.
You can use a whole set of commands to change text inside brackets / parentheses / quotation marks/ tags. It's super useful to avoid having to find the start and finish of the group. Try ci(, ci{, ci<, ci", ci', ct depending on what kind of object you want to change. And the ca(, ca{, ... variants delete the brackets / quotation marks as well.
Easy to remember: change inside a bracketed statement / change a bracketed statement.
The asterisk key, *, will search for the word under the cursor.
[+Tab will take you to the definition of a C function that's under your cursor. (It doesn't always work, though.)
Don't press Esc ever. See this answer to learn why. As mentioned above, Ctrl + C is a better alternative. I strongly suggest mapping your Caps Lock key to escape.
If you're editing a Ctags compatible language, using a tags file and :ta, Ctrl + ], etc. is a great way to navigate the code, even across multiple files. Also, Ctrl + N and Ctrl + P completion using the tags file is a great way to cut down on keystrokes.
If you're editing a line that is wrapped because it's wider than your buffer, you can move up/down using gk and gj.
Try to focus on effective use of the motion commands before you learn bad habits. Things like using 'dt' or 'd3w' instead of pressing x a bunch of times. Basically, any time that you find yourself pressing the same key repeatedly, there's probably a better/faster/more concise way of accomplishing the same thing.
Some of my latest additions to my Vim brainstore:
^wi: Jump to the tag under the cursor by splitting the window.
cib/ciB: Change the text inside the current set of parenthesis () or braces {}, respectively.
:set listchars=tab:>-,trail:_ list: Show tabs/trailing spaces visually different from other spaces. It helps a lot with Python coding.
ZZ (works like :wq)
And about the cursor position: I found that a cursor which always stays in the middle of screen is cool -
set scrolloff=9999
gv starts visual mode and automatically selects what you previously had selected.
:shell to launch a shell console from Vim. Useful when for example you want to test a script without quitting Vim. Simply hit ^d when you done with the shell console, and then you come back to Vim and your edited file.
This always cheers me up:
:help 42
vimcryption
vim -x filename.txt
You will be asked for a passphrase, edit and save. Now whenever you open the file in vi again you will have to enter the password to view.
Build and debug your code from within Vim!
Configuration
Not much, really. You need a Makefile in the current directory.
To Compile
While you're in Vim, type :make to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.
The Magic
Back within Vim, you have the following commands at your disposal:
:cl lists the errors, warnings, and other messages.
:cc displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.
:cc n jumps to the nth message.
:cn advances to the next message.
:cp jumps to the previous message.
There are more; if you're interested, type :help :cc from within Vim.
Press % when the cursor is on a quote, parenthesis, bracket, or brace to find its match.
^P and ^N
Complete previous (^P) or next (^N) text.
^O and ^I
Go to previous (^O - "O" for old) location or to the next (^I - "I" just near to "O").
When you perform searches, edit files, etc., you can navigate through these "jumps" forward and back.
Marks
Press ma (m- mark, a - name of mark). Later to return to the position, type `a.
^r^w to paste the word under the cursor in command mode.
It is really useful when using grep or replace commands.
Until [character] (t). It is useful for any command which accepts a range. My favorite is ct; or ct) which deletes everything up to the trailing semicolon / closing parentheses and then places you in insert mode.
Also, G and gg are useful (Go to bottom and top respectively).
^y will copy the character above the cursor.
Typing a line number followed by gg will take you to that line.
I wish I'd known basic visual block mode stuff earlier. Even if you don't use Vim for anything else, it can be a big time saver to open up a file in Vim just for some block operations. I'm quite sure I wasted a ton of time doing this kind of thing manually.
Examples I've found particularly useful, when, say, refactoring lists of symbolic constant names consistently:
Enter Visual Block mode (Ctrl + Q for me on Windows instead of Ctrl + V)
Move the cursor to highlight the desired block.
Then, I whatever text and press Esc to have the text inserted in front of the block on every line.
Use A instead of I to have the text inserted after the block on every line.
Also - simply toggling the case of a visual selection with ~ can be a big time saver.
And simply deleting columns, too, with d of course.
q<letter> - records a macro.
and
#<same-letter> - plays it back.
These are by far the most useful commands in Vim since you can have the computer do a whole lot of work for you, and you don't even have to write a program or anything.
Opening multiple files using tabs
:tabe filepath
Navigating between open files
gt and gT or :tabn and :tabp
Save the open session so that you can get back to your list of open files later
:mksession session_file_name.vim
Open a created session
vim -S session_file_name.vim
Close all files at once
:qa
Another command I learned recently
autocmd
It allows you to run a command on an event, so you could for example run the command make when you save a file using something like:
:autocmd BufWritePost *.cpp :make
qx will start recording keystrokes. You can do pretty much any editing task and Vim remembers it. Hit q again when you're finished, and press #x to replay your keystrokes. This is great for repetitive edits which are too complex to write a mapping for. You can have many recordings by using a character other than x.
I would have to say that one of my favorites is putting the help window in a new tab:
:tab help <help_topic>
This opens up help in a new tab and, as somebody that loves Vim tabs, this is ridiculously useful.
:x #(Save and Quit a File)
Same as :wq or ZZ
cw
Change word - deletes the word under the cursor and puts you in insert mode to type a new one. Of course this works with other movement keys, so you can do things like c$ to change to the end of the line.
f + character
Finds the next occurrence of the character on the current line. So you can do vft to select all the text up to the next "t" on the current line. It's another movement key, so it works with other commands too.
:b [any portion of a buffer name] to switch buffers. So if you have two buffers, "somefile1.txt", and "someotherfile2.txt", you can switch to the second with simply ":b 2.t<enter>". It also supports tab completion, although it's not required.
Speaking of tab completion, the setting :set wildmode=full wildmenu is also very helpful. It enables complete tab completion for command-mode, as well as a very helpful ncurses-style menu of all the possible matches when using it.

Resources