Git Grep and Open File

Git grep is a search command built around the Git ls-files command.

git ls-files | grep -v -f ignore.txt | xargs grep -n

The command line takes all the files checked into version control, strips out the unwanted files, then searches the remaining for a text string or regular expression.

The result is a list of matching lines with their filename and line numbers.

I wrote an Emacs command called slf-git-grep to run it. You select some text then press a key (ctrl+space) to find the selected text in all your source files. It opens a buffer for the results and the matching text is colored red.

This allows you to navigate your source with just a few keystrokes.

If there is no selection, it prompts you for the search string (or regular expression).

It works with multiple repositories on the same machine. Each one has its own results buffer that’s appended to.

The Git root folder is found mostly automatically by searching relative to the current file. If it cannot find it that way, it uses the Git root found last. If it still isn’t found, you are prompt for it.

You may have source checked in that you don’t want to look at. For example third party libs. You can exclude these files using ignore.txt.
The grep command looks for the ignore.txt file in the Git root directory and if not found it looks in your home folder.

The results buffer shows the relative filename and line number. This allows you to go to the found line with one keystoke (ctrl+o). That’s done using another command I wrote called slf-open-file-under-cursor.

slf-open-file-under-cursor is an emacs command which opens the file under the cursor and goes to the specified line number.

The command parses the current line to extract the filename and line number. Then it opens the file and goes to the line.

The command supports common file/line formats generated by grep, a couple stack traces and logging.

Filename is either a full path or a filename relative to the current directory.

Download from github at: