I was trying to google how to search within a scope in VIM and found this link. Limiting search scope for code in Vim
I wouldn't imagine to come up with the keyword "/\%V" to search help in VIM help. So, I'm wondering how most people get help from VIM help, like in this case.
You did the right thing. Google is probably going to be your best bet. You can also use the vim help site, it has a search function built in: http://vimdoc.sourceforge.net/htmldoc/
General:
:help help-summary is a great document explaining how to search
effectively.
Using wildcard expansion
I've had the same frustration, but I just realised that you can use wildcard
expansion when searching.
In your case it wouldn't have helped, but possibly if you'd started with :h pattern and then searched in that page for key words related to what you were
trying to achieve you might have found it.
In my case I was looking for a page I'd been on before only the other night,
:h ex-cmd-index, (on a different machine, so I couldn't search my command
history) but I could only remember than it had to do with ex commands, and had
the word index in there. I spent 20 mins trying to find it unsuccessfully (I
eventually googled it just so I could then return to vim and look it up...). I
was trying ex + Tab and being shown hundreds of possibilities...
But with wildcard expansion, I can just do :h ex*index* and hit Tab and I
get a shortlist of two possibilities, ('ex-cmd-index' and 'ex-edit-index') one
of which was the one I wanted!
So as long as you have an idea of the order that things should appear in the
help topic, you should be able to narrow down the possibilities much faster.
Using :helpgrep
There is a in-built command :helpgrep which puts every line matching a
pattern into a quickfix list. Then you can jump through each line with the
:cnext and cprev commands.
Fuzzy search the help with fzf (and optionally ag-silver-searcher)
The fzf plugin has the command :Helptags to do a fuzzy search on... the
help tags. This is very nice.
In case all the above fails, I added a few functions to search the entire
contents (not just help-tags) of all the files in the vim's help doc directory
using ag-silver-searcher and fzf.
First is a function that I found on an issue on the fzf github repo. I have no
idea how it works, but the command that calls this function allows me to search
the contents of a directory using ag, which pumps the results into fzf:
" Ag: Start ag in the specified directory e.g. :Ag ~/foo
function! s:ag_in(bang, ...)
if !isdirectory(a:1)
throw 'not a valid directory: ' .. a:1
endif
" Press `?' to enable preview window.
call fzf#vim#ag(join(a:000[1:], ' '),
\ fzf#vim#with_preview({'dir': a:1}, 'right:50%', '?'), a:bang)
endfunction
" Ag call a modified version of Ag where first arg is directory to search
command! -bang -nargs=+ -complete=dir Ag call s:ag_in(<bang>0, <f-args>)
So I wrote a function (Help_Ag) that calls the above command, and supplies
the directory containing the vim help docs (141 .txt files, plus a handful of
other files (a README, the tag files themselves etc).
If we select a help page to open, we set it to non-nomodifiable. I noticed that
not all the tags worked, and some redirected to the wrong page (e.g. a tag like
*help-topic* would take me to a page called help if the cursor was on that
word, and take me to topic if the cursor was on that word, whereas the in
real help, I would be taken to help-topic). I found that if I opened the real
help, the tags would start behaving normally in files selected with ag+fzf. So
I simply open and close the real help to trigger this behaviour (it's too quick
to even see, so I'm happy enough with this hack):
function! Help_Ag()
let orig_file = expand(#%)
let v1 = v:version[0]
let v2 = v:version[2]
" search in the help docs with ag-silver-search and fzf and open file
execute "normal! :Ag /usr/share/vim/vim".v1.v2."/doc/\<cr>"
" if we opened a help doc
if orig_file != expand(#%)
set nomodifiable
" for some reason not all the tags work unless I open the real help
" so get whichever help was found and opened through Ag
let help_doc=expand("%:t")
" open and close that help doc - now the tags will work
execute "normal! :tab :help " help_doc "\<cr>:q\<cr>"
endif
endfunction
" get some help
command! H :call Help_Ag()
Related
I had this vim configuration some time back which shows autocomplete suggestions on pressing Ctrl + N from all the files I have opened during a session, not just the current file I am editing. Unfortunately I lost the vimrc and now I can't figure out what was making it do so.
Searched over internet and found results related to omnicomplete. But I didn't understand how it works. Any help would be appreciated. Thanks.
From :help i_ctrl-n:
CTRL-N Find next match for words that start with the
keyword in front of the cursor, looking in places
specified with the 'complete' option. The found
keyword is inserted in front of the cursor.
From :help 'complete' (or <C-]> on 'complete'):
b scan other loaded buffers that are in the buffer list
Don't google, :help.
In Zsh, I can use filename completion with slashes to target a file deep in my source tree. For instance if I type:
vim s/w/t/u/f >TAB<
zsh replaces the pattern with:
vim src/wp-contents/themes/us/functions.php
What I'd like is to be able to target files the same way at the Vim command line, so that typing
:vi s/w/t/u/f >TAB<
will autocomplete to:
:vi src/wp-contents/themes/us/functions.php
I'm trying to parse the Vim docs for wildmode, but I don't see what settings would give me this. It's doing autocompletion for individual filenames, but not file paths. Does Vim support this natively? Or how can I customize the autocomplete algorithm for files?
Thanks for any advice!
-mykle-
I couldn't find a plugin to do this, so I wrote one. It's called vim-zsh-path-completion. It does what you're looking for, although via <C-s> rather than <Tab>. You can use it with <Tab> for even more control over what matches, though.
It's got bugs, but for basic paths without spaces/special characters, it should work. I think it's useful enough in its current state to be helpful. I hope to iron out the bugs and clean up the code, but I figured I'd start soliciting feedback now.
Thanks for the idea!
Original (wrong) answer, but with some useful information about Vim's wildmode.
Put the following in your .vimrc:
set wildmenu
set wildmode=list:longest
That will complete to the longest unique match on <Tab>, including appending a / and descending into directories where appropriate. If there are multiple matches, it will show a list of matches for what you've entered so far. Then you can type more characters and <Tab> again to complete.
I prefer the following setting, which completes to the first unique match on <Tab>, and then pops up a menu if you hit <Tab> again, which you can navigate with the arrow keys and hit enter to select from:
set wildmode=list:longest,list:full
Check out :help wildmenu and :help wildmode. You might also want to set wildignore to a list of patterns to ignore when completing. I have mine as:
set wildignore=.git,*.swp,*/tmp/*
Vim doesn't have such a feature by default. The closest buil-in feature is the wildmenu/wildmode combo but it's still very different.
A quick look at the script section of vim.org didn't return anything but I didn't look too far: you should dig further. Maybe it's there, somewhere.
Did you try Command-T, LustyExplorer, FuzzyFinder, CtrlP or one of the many similar plugins?
I use CtrlP and fuzzy matching can be done on filepath or filename. When done on filepath, I can use the keysequence below to open src/wp-contents/themes/us/functions.php (assuming functions.php is the only file under us that starts with a f):
,f " my custom mapping for the :CtrlP command
swtuf<CR>
edit
In thinking about a possible solution I'm afraid I was a little myopic. I was focused on your exact requirements but Vim has cool tricks when it comes to opening files!
The :e[dit] command accepts two types of wildcards: * is like the * you would use in your shell and ** means "any subdirectory".
So it's entirely possible to do:
:e s*/w*/t*/u*/f*<Tab>
or something like:
:e **/us/f<Tab>
or even:
:e **/fun<Tab>
Combined with the wildmode settings in Jim's answer, I think you have got a pretty powerful file navigation tool, here.
I have a system of navigating the code across multiple files in a huge code base, and I want to improve/fix a drawback that it currently has :
My shell is pre-configured to open at the root of my code base - lets call it Dev/.
During syncing/code building, I have a script which automatically stores the relative path of all .h and .c files in a single file to be used by cscope (lets call it cscope.files).
Once I sync, this file is updated - and then I can open any file I want in vim using the following command from Dev/ :
vif "part of file name",
where
vif: aliased to vi `grep !:1 cscope.files`
Provided I give a part of the filename long enough to uniquely identify it, I can immediately open it in vim.
Now, the drawback to this approach is, when I've already opened one file, and jump to another file without exiting vim, the only way I can do so is
:!vif *file2*
This spawns a new shell and then opens the file in a vim launched there. As a result, I can't switch between the two files (using Ctrl-^). I'm unable to come up with a solution that :
a) Lets me open any file from Dev/ instantly
b) Lets me open any other file inside vim (once I've opened an existing file) in the same shell, so that the 2 vim sessions are aware of each other (I can hop between the 2 using Ctrl-^)
I know this is a long question (how does one google this :) ), but I'm betting the solution is simple and obvious to someone more proficient in vim !!
Let me know if any part of the question is fuzzy, and I'll clarify it...
UPDATE:
I ultimately went the cscope way, after customizing using a shortcut (as using 'gf' on cscope.files still prevented me from toggling between 2 source files). See VIM 7 and cscope: Using "cscope find f" inside a keyboard mapping for switching between files for the shortcut.
Use vim's grep in something like this:
:map <F1> :vim <pattern> cscope.files<CR>gf
For example, with this:
vnoremap <F1> "ry:exe ':1vim /'.#r.'/ cscope.files'<CR>gf
you select (visual mode) the pattern you'd like to search for and then press F1. The first file that matches the pattern will open, replacing the current buffer*.
* If this is possible. i.e if current buffer is saved or if hidden is set etc.
If you prefer to get a prompt, use input():
nnoremap <F1> :exe ':1vim /'.input("Enter pattern: ").'/ cscope.files'<CR>
[ but then you have to manually gf because input() consumes the remaining characters of the map. To avoid this, you can use inputsave() and inputrestore() ]
update
... for example like this:
function! GetPat()
call inputsave()
let mypat = input("Enter pattern: ")
call inputrestore()
return mypat
endfunction
nnoremap <F1> :exe ':1vim /'.GetPat().'/ cscope.files'<CR>gf
I think that the Vim Fuzzy Finder plugin is well adapted to your use case.
As the name implies, using the plugin, you can find files using a fuzzy text search.
Additionnaly, it also works for other Vim ressources like buffers, tags, etc.
I don't use cscope myself, but it seems that you can use it to find files, see :help cscope-find.
Otherwise, something like (not tested) this could help:
"Custom function
function! MyFunc(pat)
" Get files list
let filelist = readfile('path/to/cscope.files')
" Filter non matching item out and see if only one item is left
if len(filter(filelist, 'v:var =~? '.a:pat)) == 1
" edit file
exec 'edit '.filelist[0]
else
" Report back
echom 'More than one match:'
for file in filelist
echom file
endfor
endif
endfunction
" Custom command
command! -bar -nargs=1 MyCom call MyFunc(<args>)
Also try using the built-in cscope integration:
:cs find f stdio.h
Cscope tag: stdio.h
# line filename / context / line
1 1 /usr/include/stdio.h <<<unknown>>>
2 1 /usr/include/bits/stdio.h <<<unknown>>>
Type number and <Enter> (empty cancels):
See :help cscope-suggestions for some mappings that may make it easier to use cscope from within vim.
If I do either of the following two:
call search("searchString")
exec "/ searchString"
From a script, then vim does the search but does not highlight the results, even though hlsearch. Doing the same searches from outside a script highlights the results.
Just found out the answer myself:
call search(l:searchString)
call matchadd('Search', l:searchString)
The
feedkeys()
function is the key (pun intended):
call feedkeys("/pattern\<CR>")
or cleaner:
" highlights – or doesn’t – according to 'hlsearch' option
function SearcH(pattern)
let #/ = a:pattern
call feedkeys("/\<CR>")
endfunction
I know this is late. However when I searched for the answer to this problem this page came up. So I feel compelled to help fix it.
call search(l:searchString)
call matchadd('Search', l:searchString)
Did not work for me. (when run from inside a function) It did higlight the words I wanted to search for but n/N wouldn't cycle between them. Also when I performed a new search the "l:serachStirng" pattern still remained highlighted. This answer on this link worked much better
Vim search and highlighting control from a script
Which gave me:
let #/ = l:searchString
then run
normal n
outside the funciton (so the highlighting is done immediately without the user needing to press n)
To turn on, press ESC type :set hls
To turn off, press ESC type :set nohls
Found answer here:
http://vim.1045645.n5.nabble.com/highlighting-search-results-from-within-a-function-tt5709191.html#a5709193
```
One solution would be
function! XXXX()
execute '/this'
return #/
endfunction
and to use the following instead of ":call XXXX()".
:let #/ = XXXX()
```
I believe this works from inside a function
(to just enable highlighting and nothing more):
call feedkeys(":\<C-u>set hlsearch \<enter>")
You need to put this in your .vimrc file
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
The .vimrc file is usually located in your home directory, or you can find it using "locate .vimrc"
So I'm basically a beginner when it comes to Vim, nonetheless I do know the basic things (open files, edit, move around, basic grep, .vimrc, etc)
I would submit this link first
http://weblog.jamisbuck.org/2008/11/17/vim-follow-up
If you scroll down to where it says "NERD___tree", it explains what it is and gives a link to the home page. I have already gotten NERD_tree installed, so far so good.
Only thing is, this guy (JamisBuck) adds a line to the .vimrc file to streamline it's usage (I'm guessing to toggle between NERD_tree and the actual file, because as far as I can tell, there is no quick way to do it other than typing in:
:NERDTree
Every time which is less than desirable. The follwing is the code he adds to the .vimrc file:
map <leader>d :execute 'NERDTreeToggle ' . getcwd()<CR>
He doesn't explain exactly what is is and/or how to use it, so If someone could give me a short explanation and/or point me towards a resource to learn more about this, that would be appreciated.
I'd say :help leader will give you what you need, is an anti-slash by default.
Thus, map <leader>d will be launched when you do \d.
According to the vim documentation, the
<Leader>
Is a special variable that is replaced with the value of "mapleader" at the time the mapping is defined. So:
map <leader>d :execute 'NERDTreeToggle ' . getcwd()<CR>
Is mapping the mapleader and "d" to the toggle. If you look at the page you linked, earlier in the page he says:
I’ve got my <Leader> character (:h mapleader) mapped to the comma
(since it’s easier to reach than the backspace character).
let mapleader = ","
So the toggle should be ",d" as far as I can tell.
In addition to what others have said (d mapped to the command), the command, itself:
:execute 'NERDTreeToggle ' . getcwd()<CR>
Is simply executing the NERDTreeToggle command with the first argument as the current working directory. The at the end is a carriage return, and is just simulating a press of the enter key.
This means that when NERD tree opens, it will be in the current working directory.