how to leave search mode in VIM? - vim

Given a file like the following:
blah
blah
collection = getCollection();
process(somethingInTheWay, target);
...after this short sequence of 'search' commands in vim...
/col<carriage return>
My cursor will be under the first appearance of "collection."
Now, what command(s) will remove the '/col' from my vim command line (in case I want to search afresh, for example)?

There are a couple of things that play a role here. Your input ("/col") is displayed in the command line for some extra time after search. Usually people don't care about this. After some time, some find it even helpful. You already left "search mode" when you pressed Enter and after vim put the cursor on the first match. vim will lazily remove the search string when redrawing screen or when the space is needed. There are some ways to remove it manually, if you want to:
Ctrl-L (redraw)
:redraw
any combination of / or : with Esc or Backspace
Now I wrote, that you already left "search mode" with Enter, but you may continue your last search at any time with n / N. These commands will just take whatever is in the special register / and use it for further searching. It would be possible to "disable" this behaviour by removing the last search pattern from /:
:let #/ = ""
You could manually put something into that register which would enable you to "continue search" without ever having started any search.
If you just want to get rid of the currently highlighted matches, type:
:noh
You can turn off or toggle highlighting matches in general:
:set nohls
:set hls!
The latter is a good candidate for a key binding. I use this to toggle highlighting of the last search (mnemonic: klear - not very accurate but works for me):
:nno <C-k> :set hls!<CR>

Related

Cycling and/or highlighting through a vim selection

The feature I am thinking of is kind of inspired by a feature that I really like about sublime text.
In sublime text, if you select a sequence of characters, it automatically puts a little box around it (to distinguish it from the word that you just highlighted). For me, this is very helpful because I can see and find specific things of the code much faster.
It would be awesome to have something similar to my vim environment. It does not have to be exactly the same as the one in sublime though, but it would be awesome if it were as similar as possible plus the additional feature to easy cycling through similar words.
Currently, what I am doing is highlight the work I want and then manually typing it to the search command /. It would be much better if I can just highlight it in visual mode and then automatically highlight similar words on the current screen with a different colour from the highlighting in visual mode and then have a quick key short cut to cycling through them, if I wished to do that.
I am not sure if a there exists a plugin or something that already does that, but that would cool! Ideally, I would want to to know as many details of the commands/changes to the vimrc file, so that I have the most control over this feature and be able to customize it as I wish.
You can get the highlighting you are looking for by enabling the hlsearch option:
:set hlsearch
It will highlight every occurrence of the last search pattern and thus work after all the following commands (and their relatives):
/foo<CR>
?bar<CR>
:s/fizz/buzz/g
*
#
You can use n to jump to the next occurrence in the direction of your search and N to do the same in the opposite direction.
To highlight every occurrence of the current word "without" moving the cursor, you can simply do:
*N
or:
*``
to jump to the next occurrence and jump back immediately.
Doing the same for visually selected text is a bit trickier but still possible…
either via a lightweight plugin like visualstar or The Search Party,
or with a tiny bit of crude vimscript in your ~/.vimrc:
" this function cleans up the search pattern
function! GetVisualSelection()
let old_reg = #v
normal! gv"vy
let raw_search = #v
let #v = old_reg
return substitute(escape(raw_search, '\/.*$^~[]'), "\n", '\\n', "g")
endfunction
" map * and # in visual mode so that they do the same as *N and #N in normal mode
xnoremap * :<C-u>/<C-r>=GetVisualSelection()<CR><CR>N
xnoremap # :<C-u>?<C-r>=GetVisualSelection()<CR><CR>N
My SearchHighlighting plugin changes the * command so that it just toggles the highlighting for the current word, without the movement to the next match (for which you can press n, or pass a count). This also works in visual mode, using the selection. I find this very handy for highlighting all matches.
There's also a mode that automatically highlights the current word / selection, like what many IDEs offer.
Other plugins
If you want more permanent highlighting, separate from searching, the Mark plugin offers that.
To get an orientation about the number of matches (without highlighting them), I have the SearchPosition plugin.

Omnicompletion search suggestions

Is there any way to configure Omnicompletion for / searches? So searching for /be would suggest other words in the text such as:
/be<tab>
Beatles
beer
Beethoven
personally, I think after typing / you can type a regex, auto-completion doesn't make much sense here... vim doesn't know what you want to have, how can it give suggestions? It is not like in Insert mode.
However there is way to achieve it.
you type /
you type Ctrl-F
you type i (go into insert mode)
you type beTAB
now you see the popup menu.
this works not only for /, but also for : (cmd mode)
Ctrl-F is handy when we write long commands
detail:
:h cedit
You can use the CmdlineComplete plugin.
It will be triggered with <C-n> / <C-p>, and won't show a completion menu (but you can cycle through candidates by repeating the trigger).
You can use a combination of 'incsearch' and command-line completion with CtrlR CtrlW (:h c_CTRL-R_CTRL-W) to achieve something quite close to what you want:
:set incsearch.
Start typing your search pattern, e.g. /Be. The cursor moves to the next potential match as you type.
As soon as the cursor lands on the word you want to complete, hit CtrlR CtrlW. This pulls the word down into your search prompt: it effectively "completes" your search pattern.
At stage 3 you could also use these variants instead:
CtrlR CtrlA (:h c_CTRL-R_CTRL-A) pulls down the WORD instead of the word.
CtrlL (:h c_CTRL-L) completes character by character.
I used the aforementioned CmdLineComplete plugin until I learned about
set incsearch

"Find next" in Vim

To search forward in Vim for cake, I'd type /cake, but the cursor jumps to the first match when I press return. Is there a Vim command analogous to "find next"?
It is n for next and N for previous.
And if you use reverse search with ? (for example, ?cake) instead of /, it is the other way round.
If it is installed on your system, you should try to run vimtutor command from your terminal, which will start a tutorial of the basic Vim commands.
Rob Wells advice about * and # is also very pertinent.
The most useful shortcut in Vim, IMHO, is the * key.
Put the cursor on a word and hit the * key and you will jump to the next instance of that word.
The # key does the same, but it jumps to the previous instance of the word.
It is truly a time saver.
When I was beginning I needed to watch a demo.
How to search in Vim
type /
type search term e.g. "var"
press enter
for next instance press n (for previous N)
You may be looking for the n key.
Typing n will go to the next match.
As discussed, there are several ways to search:
/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)
plus, navigating prev/next with N and n.
You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.
Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:
hi Search ctermfg=yellow ctermbg=red guifg=...
But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:
nmap <leader>z :noh<CR>
I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.
If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

How do I make Vim do normal (Bash-like) tab completion for file names?

When I'm opening a new file in Vim and I use tab completion, it completes the whole file name instead of doing the partial match like Bash does. Is there an option to make this file name tab completion work more like Bash?
I personally use
set wildmode=longest,list,full
set wildmenu
When you type the first tab hit, it will complete as much as possible. The second tab hit will provide a list. The third and subsequent tabs will cycle through completion options so you can complete the file without further keys.
Bash-like would be just
set wildmode=longest,list
but the full is very handy.
The closest behavior to Bash's completion should be
set wildmode=longest:full,full
With a few character typed, pressing tab once will give all the matches available in wildmenu. This is different to the answer by Michael which opens a quickfix-like window beneath the command-line.
Then you can keep typing the rest of the characters or press tab again to auto-complete with first match and circle around it.
Apart from the suggested wildmode/wildmenu, Vim also offers the option to show all possible completions by using Ctrl + D. This might be helpful for some users that stumble across this question when searching for different autocompletion options in Vim like I did.
If you don't want to set the wildmenu, you can always press Ctrl + L when you want to open a file. Ctrl + L will complete the filename like Bash completion.
I'm assuming that you are using autocomplete in Vim via Ctrl + N to search through the current buffer. When you use this command, you get a list of solutions; simply repeat the command to go to the next item in the list. The same is true for all autocomplete commands. While they fill in the entire word, you can continue to move through the list until you arrive at the one you wish to use.
This may be a more useful command: Ctrl + P. The only difference is that Ctrl + P searches backwards in the buffer while Ctrl + N searches forwards... Realistically, they will both provide a list with the same elements, and they may just appear in a different order.
set wildmode=longest:full gives you a Bash-like completion with:
suggestions in a single line
Tab completing only what is certain
Right/Ctrl-n | Left/Ctrl-p to select suggestions.
From the help:
If you prefer the <Left> and <Right> keys to move the cursor instead
of selecting a different match, use this:
:cnoremap <Left> <Space><BS><Left>
:cnoremap <Right> <Space><BS><Right>
Try using :set wildmenu. Apart from that, I'm not sure what exactly you're trying.
Oh, yeah, and maybe try this link: link

Vim / vi Survival Guide

What are the essential vim commands? What does a new-user need to know to keep themselves from getting into trouble? One command per comment, please.
What I find irreplaceable (because it works in vi also, unlike vim's visual mode) are marks. You can mark various spots with m (lower case) and then a letter of your choice (eg x). Then you go elsewhere, and can go back with ``x(backquote letter) to the exact spot, or with'x` (apostrophe letter) to go to the line.
These movements can be used as arguments to commands (yank, delete, etc). For example, you want to delete 10 lines; instead of counting and then moving to the topmost line and entering 10dd, you go to either the start or the end of the block, press mm (mark m), then go to the other end of the block, and press d'm (delete apostrophe m). If you use backquote instead of apostrophe in this example, then the deletion will work character-wise, not line-wise. Try marking in the middle of the line with "mark m", moving to the middle of another line, then entering "d backquote m" and you will see what I mean.
I was very happy the day I learned about using * or # to search, down or up respectively, for the word under the cursor. Make sure to :set incsearch and :set hlsearch first.
I like this QRC!
http://www.fsckin.com/wp-content/uploads/2007/10/vi-vim_cheat_sheet.gif
When you have some repetitive action to take Macros are usually faster than regex.
Just type
q[0-9a-z] in normal mode
Many people use
qq
because it's fast.
Press
q in normal mode
again to stop recording.
Then just type
#[0-9a-z] in normal mode
to repeat what you just recorded.
#q
for the example like above.
Edited to add: you can also repeat the macro. Let's say you programed a macro to jump to the head of a line, insert a tab, and then jump down one line. You then test your macro by typing "#q" to run it once. Then you can repeat the action nine more times by typing "9#q".
:q -> quit
:w -> save
:q! -> quit and don't save
:x -> save and quit
:[number] -> go to line number
G -> go to end of file
dd -> delete line
p -> "put" line
yy -> "copy" line
:s/[searchfor] -> search
I guess those are the basic one to start from
Use the 'J' (J for Join; upper-case) command to delete the newline at the end of a line. You'll find it tricky otherwise.
This recent Vim tutorial from IBM is pretty good
First of all you need to know how to close vi:
ctrl-c : q!
Rest can be found from vimtutor. Launch vimtutor by typing vimtutor at your command line
Although this is a matter of personal preference I've found that one of the essential things to do is to remap Esc to something else.
I find it very uncomfortable to reach for the Esc key to exit insert mode, but the beautiful thing about Vim is that allows key mappings.
I'm currently using the following mapping using Control + S:
inoremap <C-s> <Esc>:w<CR>
This has the advantage of being a key mapping I have already committed to memory and has the added value of saving my work every time I go to normal mode. Yeah, I know it is crazy but I would be hitting the save command that frequently anyway. It's like a bad habit, you know.
" ~/.vimrc
" Turn on line numbering
set nu
" Turn on syntax highlighting
syntax on
" Set 4 space expanding tabs
set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
"turn off line wrapping
set nowrap
" Map CTRL-N to create a new tab
:map <C-n> <ESC>:tabnew<RETURN>
" Map Tab and CTRL-Tab to move between tabs
:map <Tab> <ESC>:tabn<RETURN>
:map <C-Tab> <ESC>:tabp<RETURN>
If you're using vim, the 'u' command (in command mode) will Undo the last command you typed. You can use this command repeatedly to undo mistakes you may have made before saving the file.
See http://www.rayninfo.co.uk/vimtips.html for a great collection of Vim tips, from the basic can't-live-without to very sophisticated stuff that you might never have thought of trying.
Lots of great commands are listed at the Vim Tips Wiki.
It's also good to run the vimtutor when learning these commands
alias vi nedit :)
all humor aside..
for vi WHEN NOT using nedit..
i (switch to insert mode)
a (append = move to end of line and switch to insert mode)
esc (exit insert mode)
dd delete a line
x delete a character
:wq (save and quit)
/ start a search
n find Next
? search backwards..
yy (yank) copy a line to the buffer
pp (paste) paste it here
r (replace a character)
<N> <command> this is a neat - but aggravating feature that lets you type digits and then a command so
5dd will delete 5 lines
but at this point you might as well
- man vi and refresh your memory
While there are LOTS more, I switched from Vi to nedit several years ago, which I find has more features I can use on a regular basis more easily. Tabbed editing, incremental search bar, column select, copy and paste. sort selected lines, search and destroy within selection, whole doc or all open docs..
tear-off drop down menus..
and it supports syntax highlighting for all the languages I use.. (with pattern files I've used a long time over the years. VIM many now be equivalent, but It has to introduce a feature that Nedit doesn't and an easy way to migrate my pattern files before I switch again.
I like the Vim 5.6 Reference Guide, by Bram Moolenaar and Oleg Raisky.
You can directly print it in booklet form, easy to read, I always have it laying around.
It's a tad old, but what are 8 years in Vi's lifespan ?
:set ignorecase smartcase
Makes searching case-insensitive, unless your search includes a capital letter. Not the most indispensable perhaps, but I find myself setting this option any time I'm editing in a new place. It's in any vimrc file I own.
:%!xxd
View the contents of a buffer in hexadecimal. To revert:
:%!xxd -r
My biggest tip: ctrl+q saves the day when you accidentally hit ctrl+s to save the file you are working on
I have this in my vimrc
set number
set relativenumber
This gives me a line numbering system which makes j, k keys really productive.
I use vi very lightly, and I only use the following commands:
a - switch to insert mode (after the cursor)
esc - return to command mode
:wq - save and quit
:q - quit (no save, only without modification)
:q! - force quit (no save, also with modification)
x - delete one character (in command mode)
dd - delete the whole line (in command mode)
I know there are many many more, but those are enough to get you by.
One of my favourite commands is %G which takes to directly to the end of a file. Especially useful in log-files.
How to switch between modes (i to enter insert mode (one of many ways), esc to exit insert mode, colon for command mode) and how to save and exit. (:wq)
Another useful command is to search something: /
e.g. /Mon will search (and in case of vim highlight) any occurences of Mon in your file.
As a couple of other people have already mentioned, vimtutor is the way to go. It will teach you everything you need to know in vim. The one piece of general advice I would give you is to stay out of insert mode as much as possible. There is enormous power in the other modes, it just takes a little bit of practice to get used to it.
i - insert mode (escape to exit)
dd - delete line
shift-y - 'Yank' (copy) line
p - 'Put' (paste) line(s)
shift-v - Visual mode used to select text (tryin 'yanking' this text and 'putting' it somewhere.
ctrl-w n - create new window (you can open a file or start new file here)
ctrl-w v - split existing window vertically
ctrl-n (in insert mode) - autocomplete (if supported)
:! to run a shell command, usually with standard in as the file or a selection (shift-V)
Useful plugins to look at:
* Buffer Explorer - use \be to view files in the buffer (and select to re-open)
NB vi is not vim! vim is rapidly turning into the emacs of the new century. nvi is probably the closest thing to the original vi. Here's a nice hint: "xp" will exchange two characters (try it).
replace 'foo' with 'bar' everywhere in the file
:%s/foo/bar/gc
The real power is in the searching. Here are the essential commands:
/Steve will find the first instance of "Steve" in the text.
n will find the next "Steve" in the text.
:%s//Stephen/g will replace all those instances of "Steve" you just searched for with "Stephen".
Not to promote myself, but I wrote a blog post on this subject. It focuses on the critical parts of Vim for a beginner.
My favorites:
% find matching bracket/brace
* and # next/previous match
gg top of page
G end of the page
<Ctrl-v> Change to visual mode and select column
<Ctrl-a> increase current number by 1
<Ctrl-x> decrease current number by 1
Running macros

Resources