Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search whole project by default with Vim/Ack

Tags:

vim

ack

I would like to use Ack (or similar plugin if something else can do the job) to search my whole project in Vim by default, rather than just the current directory. Ideally I'd end up with a process that works like using Cmd+Shift+F in Sublime. How can I do this?

An option like CtrlP's let g:ctrlp_working_path_mode = 'r' that makes it search within the nearest parent directory that contains a file like .git would be perfect. (https://github.com/kien/ctrlp.vim#basic-options)

like image 390
RobHeaton Avatar asked Oct 15 '13 09:10

RobHeaton


People also ask

How do I search for a project in Vim?

From the root of your project, you can search through all your files recursively from the current directory like so: grep -R '. ad' . The -R flag is telling grep to search recursively.

What is Vimgrep?

vimgrep is Vim's built-in command for searching across multiple files. It's not so fast as external tools like ack and git-grep, but it has its uses. vimgrep uses Vim's built-in regex engine, so you can reuse the patterns that work with Vim's standard search command.

What is CW in Vim?

In a nutshell: <number of times> + <command> + <text object or motion> With that in mind, there are 3 different ways you can change words in Vim: cw – Change from cursor to the end of the word. caw – Change around the word, including trailing whitespace.


3 Answers

I think Rooter is what you want. For example:

let g:rooter_patterns = ['Rakefile', '.git/']
like image 116
basteln Avatar answered Oct 14 '22 03:10

basteln


I don't think Ack (or grep/vimgrep) can detect your "project root". If you often work on several projects, you could add this block in your vimrc:

let g:projectA_path="/path/to/A"
let g:projectB_path="/path/to/B"
let g:projectC_path="/path/to/C"

also define some functions/commands, like AckA, AckB, AckC... basically the func/command just does:

exec 'Ack! '. pattern . " " . g:projectA_path

the pattern is the argument you passed in. then, in future, you could do:

:AckA foo

or

:call AckA("foo")

for quick grepping/acking in projectA.

I didn't think of a simpler way to do it. glad to see if there is better solution.

like image 2
Kent Avatar answered Oct 14 '22 03:10

Kent


Most of the time I don't need to cd the project root, but stay in the same working directory. So there is a simpler solution, based on answer of Kent, without cd'ing the project root, installing additional plugins and using ag:

let g:ackprg = 'ag --vimgrep --smart-case'

function! Find_git_root()
  return system('git rev-parse --show-toplevel 2> /dev/null')[:-2]
endfunction

command! -nargs=1 Ag execute "Ack! <args> " . Find_git_root()

And to use it call :Ag <keyword>

like image 1
bogem Avatar answered Oct 14 '22 04:10

bogem