GUIDE.md
This file
Path
GUIDE.md
1,025 lines · 39.9 KiB · Markdown
Last changed by
docs: update GUIDE to use `lexopt`Andrew Gallantbefore adoptionc28ce76
History of this fileTake it
1## User Guide23This guide is intended to give an elementary description of ripgrep and an4overview of its capabilities. This guide assumes that ripgrep is5[installed](README.md#installation)6and that readers have passing familiarity with using command line tools. This7also assumes a Unix-like system, although most commands are probably easily8translatable to any command line shell environment.91011### Table of Contents1213* [Basics](#basics)14* [Recursive search](#recursive-search)15* [Automatic filtering](#automatic-filtering)16* [Manual filtering: globs](#manual-filtering-globs)17* [Manual filtering: file types](#manual-filtering-file-types)18* [Replacements](#replacements)19* [Configuration file](#configuration-file)20* [File encoding](#file-encoding)21* [Binary data](#binary-data)22* [Preprocessor](#preprocessor)23* [Common options](#common-options)242526### Basics2728ripgrep is a command line tool that searches your files for patterns that29you give it. ripgrep behaves as if reading each file line by line. If a line30matches the pattern provided to ripgrep, then that line will be printed. If a31line does not match the pattern, then the line is not printed.3233The best way to see how this works is with an example. To show an example, we34need something to search. Let's try searching ripgrep's source code. First35grab a ripgrep source archive from36https://github.com/BurntSushi/ripgrep/archive/0.7.1.zip37and extract it:3839```40$ curl -LO https://github.com/BurntSushi/ripgrep/archive/0.7.1.zip41$ unzip 0.7.1.zip42$ cd ripgrep-0.7.143$ ls44benchsuite grep tests Cargo.toml LICENSE-MIT45ci ignore wincolor CHANGELOG.md README.md46complete pkg appveyor.yml compile snapcraft.yaml47doc src build.rs COPYING UNLICENSE48globset termcolor Cargo.lock HomebrewFormula49```5051Let's try our first search by looking for all occurrences of the word `fast`52in `README.md`:5354```55$ rg fast README.md5675: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement5788: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while58119:### Is it really faster than everything else?59124:Summarizing, `ripgrep` is fast because:60129: optimizations to make searching very fast.61```6263(**Note:** If you see an error message from ripgrep saying that it didn't64search any files, then re-run ripgrep with the `--debug` flag. One likely cause65of this is that you have a `*` rule in a `$HOME/.gitignore` file.)6667So what happened here? ripgrep read the contents of `README.md`, and for each68line that contained `fast`, ripgrep printed it to your terminal. ripgrep also69included the line number for each line by default. If your terminal supports70colors, then your output might actually look something like this screenshot:7172[](https://burntsushi.net/stuff/ripgrep-guide-sample.png)7374In this example, we searched for something called a "literal" string. This75means that our pattern was just some normal text that we asked ripgrep to76find. But ripgrep supports the ability to specify patterns via [regular77expressions](https://en.wikipedia.org/wiki/Regular_expression). As an example,78what if we wanted to find all lines have a word that contains `fast` followed79by some number of other letters?8081```82$ rg 'fast\w+' README.md8375: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement84119:### Is it really faster than everything else?85```8687In this example, we used the pattern `fast\w+`. This pattern tells ripgrep to88look for any lines containing the letters `fast` followed by *one or more*89word-like characters. Namely, `\w` matches characters that compose words (like90`a` and `L` but unlike `.` and ` `). The `+` after the `\w` means, "match the91previous pattern one or more times." This means that the word `fast` won't92match because there are no word characters following the final `t`. But a word93like `faster` will. `faste` would also match!9495Here's a different variation on this same theme:9697```98$ rg 'fast\w*' README.md9975: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement10088: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while101119:### Is it really faster than everything else?102124:Summarizing, `ripgrep` is fast because:103129: optimizations to make searching very fast.104```105106In this case, we used `fast\w*` for our pattern instead of `fast\w+`. The `*`107means that it should match *zero* or more times. In this case, ripgrep will108print the same lines as the pattern `fast`, but if your terminal supports109colors, you'll notice that `faster` will be highlighted instead of just the110`fast` prefix.111112It is beyond the scope of this guide to provide a full tutorial on regular113expressions, but ripgrep's specific syntax is documented here:114https://docs.rs/regex/*/regex/#syntax115116117### Recursive search118119In the previous section, we showed how to use ripgrep to search a single file.120In this section, we'll show how to use ripgrep to search an entire directory121of files. In fact, *recursively* searching your current working directory is122the default mode of operation for ripgrep, which means doing this is very123simple.124125Using our unzipped archive of ripgrep source code, here's how to find all126function definitions whose name is `write`:127128```129$ rg 'fn write\('130src/printer.rs131469: fn write(&mut self, buf: &[u8]) {132133termcolor/src/lib.rs134227: fn write(&mut self, b: &[u8]) -> io::Result<usize> {135250: fn write(&mut self, b: &[u8]) -> io::Result<usize> {136428: fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) }137441: fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) }138454: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {139511: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {140848: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {141915: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {142949: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {1431114: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {1441348: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {1451353: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {146```147148(**Note:** We escape the `(` here because `(` has special significance inside149regular expressions. You could also use `rg -F 'fn write('` to achieve the150same thing, where `-F` interprets your pattern as a literal string instead of151a regular expression.)152153In this example, we didn't specify a file at all. Instead, ripgrep defaulted154to searching your current directory in the absence of a path. In general,155`rg foo` is equivalent to `rg foo ./`.156157This particular search showed us results in both the `src` and `termcolor`158directories. The `src` directory is the core ripgrep code where as `termcolor`159is a dependency of ripgrep (and is used by other tools). What if we only wanted160to search core ripgrep code? Well, that's easy, just specify the directory you161want:162163```164$ rg 'fn write\(' src165src/printer.rs166469: fn write(&mut self, buf: &[u8]) {167```168169Here, ripgrep limited its search to the `src` directory. Another way of doing170this search would be to `cd` into the `src` directory and simply use `rg 'fn171write\('` again.172173174### Automatic filtering175176After recursive search, ripgrep's most important feature is what it *doesn't*177search. By default, when you search a directory, ripgrep will ignore all of178the following:1791801. Files and directories that match glob patterns in these three categories:181 1. `.gitignore` globs (including global and repo-specific globs). This182 includes `.gitignore` files in parent directories that are part of the183 same `git` repository. (Unless the `--no-require-git` flag is given.)184 2. `.ignore` globs, which take precedence over all gitignore globs185 when there's a conflict. This includes `.ignore` files in parent186 directories.187 3. `.rgignore` globs, which take precedence over all `.ignore` globs188 when there's a conflict. This includes `.rgignore` files in parent189 directories.1902. Hidden files and directories.1913. Binary files. (ripgrep considers any file with a `NUL` byte to be binary.)1924. Symbolic links aren't followed.193194All of these things can be toggled using various flags provided by ripgrep:1951961. You can disable all ignore-related filtering with the `--no-ignore` flag.1972. Hidden files and directories can be searched with the `--hidden` (`-.` for198short) flag.1993. Binary files can be searched via the `--text` (`-a` for short) flag.200 Be careful with this flag! Binary files may emit control characters to your201 terminal, which might cause strange behavior.2024. ripgrep can follow symlinks with the `--follow` (`-L` for short) flag.203204As a special convenience, ripgrep also provides a flag called `--unrestricted`205(`-u` for short). Repeated uses of this flag will cause ripgrep to disable206more and more of its filtering. That is, `-u` will disable `.gitignore`207handling, `-uu` will search hidden files and directories and `-uuu` will search208binary files. This is useful when you're using ripgrep and you aren't sure209whether its filtering is hiding results from you. Tacking on a couple `-u`210flags is a quick way to find out. (Use the `--debug` flag if you're still211perplexed, and if that doesn't help,212[file an issue](https://github.com/BurntSushi/ripgrep/issues/new).)213214ripgrep's `.gitignore` handling actually goes a bit beyond just `.gitignore`215files. ripgrep will also respect repository specific rules found in216`$GIT_DIR/info/exclude`, as well as any global ignore rules in your217`core.excludesFile` (which is usually `$XDG_CONFIG_HOME/git/ignore` on218Unix-like systems).219220Sometimes you want to search files that are in your `.gitignore`, so it is221possible to specify additional ignore rules or overrides in a `.ignore`222(application agnostic) or `.rgignore` (ripgrep specific) file.223224For example, let's say you have a `.gitignore` file that looks like this:225226```227log/228```229230This generally means that any `log` directory won't be tracked by `git`.231However, perhaps it contains useful output that you'd like to include in your232searches, but you still don't want to track it in `git`. You can achieve this233by creating a `.ignore` file in the same directory as the `.gitignore` file234with the following contents:235236```237!log/238```239240ripgrep treats `.ignore` files with higher precedence than `.gitignore` files241(and treats `.rgignore` files with higher precedence than `.ignore` files).242This means ripgrep will see the `!log/` whitelist rule first and search that243directory.244245Like `.gitignore`, a `.ignore` file can be placed in any directory. Its rules246will be processed with respect to the directory it resides in, just like247`.gitignore`.248249To process `.gitignore` and `.ignore` files case insensitively, use the flag250`--ignore-file-case-insensitive`. This is especially useful on case insensitive251file systems like those on Windows and macOS. Note though that this can come252with a significant performance penalty, and is therefore disabled by default.253254For a more in depth description of how glob patterns in a `.gitignore` file255are interpreted, please see `man gitignore`.256257258### Manual filtering: globs259260In the previous section, we talked about ripgrep's filtering that it does by261default. It is "automatic" because it reacts to your environment. That is, it262uses already existing `.gitignore` files to produce more relevant search263results.264265In addition to automatic filtering, ripgrep also provides more manual or ad hoc266filtering. This comes in two varieties: additional glob patterns specified in267your ripgrep commands and file type filtering. This section covers glob268patterns while the next section covers file type filtering.269270In our ripgrep source code (see [Basics](#basics) for instructions on how to271get a source archive to search), let's say we wanted to see which things depend272on `lexopt`, our argument parser.273274We could do this:275276```277$ rg lexopt278[lots of results]279```280281But this shows us many things, and we're only interested in where we wrote282`lexopt` as a dependency. Instead, we could limit ourselves to TOML files,283which is how dependencies are communicated to Rust's build tool, Cargo:284285```286$ rg lexopt -g '*.toml'287Cargo.toml28857:lexopt = "0.3.0"289```290291The `-g '*.toml'` syntax says, "make sure every file searched matches this292glob pattern." Note that we put `'*.toml'` in single quotes to prevent our293shell from expanding the `*`.294295If we wanted, we could tell ripgrep to search anything *but* `*.toml` files:296297```298$ rg lexopt -g '!*.toml'299[lots of results]300```301302This will give you a lot of results again as above, but they won't include303files ending with `.toml`. Note that the use of a `!` here to mean "negation"304is a bit non-standard, but it was chosen to be consistent with how globs in305`.gitignore` files are written. (Although, the meaning is reversed. In306`.gitignore` files, a `!` prefix means whitelist, and on the command line, a307`!` means blacklist.)308309Globs are interpreted in exactly the same way as `.gitignore` patterns. That310is, later globs will override earlier globs. For example, the following command311will search only `*.toml` files:312313```314$ rg lexopt -g '!*.toml' -g '*.toml'315```316317Interestingly, reversing the order of the globs in this case will match318nothing, since the presence of at least one non-blacklist glob will institute a319requirement that every file searched must match at least one glob. In this320case, the blacklist glob takes precedence over the previous glob and prevents321any file from being searched at all!322323324### Manual filtering: file types325326Over time, you might notice that you use the same glob patterns over and over.327For example, you might find yourself doing a lot of searches where you only328want to see results for Rust files:329330```331$ rg 'fn run' -g '*.rs'332```333334Instead of writing out the glob every time, you can use ripgrep's support for335file types:336337```338$ rg 'fn run' --type rust339```340341or, more succinctly,342343```344$ rg 'fn run' -trust345```346347The way the `--type` flag functions is simple. It acts as a name that is348assigned to one or more globs that match the relevant files. This lets you349write a single type that might encompass a broad range of file extensions. For350example, if you wanted to search C files, you'd have to check both C source351files and C header files:352353```354$ rg 'int main' -g '*.{c,h}'355```356357or you could just use the C file type:358359```360$ rg 'int main' -tc361```362363Just as you can write blacklist globs, you can blacklist file types too:364365```366$ rg lexopt --type-not rust367```368369or, more succinctly,370371```372$ rg lexopt -Trust373```374375That is, `-t` means "include files of this type" where as `-T` means "exclude376files of this type."377378To see the globs that make up a type, run `rg --type-list`:379380```381$ rg --type-list | rg '^make:'382make: *.mak, *.mk, GNUmakefile, Gnumakefile, Makefile, gnumakefile, makefile383```384385By default, ripgrep comes with a bunch of pre-defined types. Generally, these386types correspond to well known public formats. But you can define your own387types as well. For example, perhaps you frequently search "web" files, which388consist of JavaScript, HTML and CSS:389390```391$ rg --type-add 'web:*.html' --type-add 'web:*.css' --type-add 'web:*.js' -tweb title392```393394or, more succinctly,395396```397$ rg --type-add 'web:*.{html,css,js}' -tweb title398```399400The above command defines a new type, `web`, corresponding to the glob401`*.{html,css,js}`. It then applies the new filter with `-tweb` and searches for402the pattern `title`. If you ran403404```405$ rg --type-add 'web:*.{html,css,js}' --type-list406```407408Then you would see your `web` type show up in the list, even though it is not409part of ripgrep's built-in types.410411It is important to stress here that the `--type-add` flag only applies to the412current command. It does not add a new file type and save it somewhere in a413persistent form. If you want a type to be available in every ripgrep command,414then you should either create a shell alias:415416```417alias rg="rg --type-add 'web:*.{html,css,js}'"418```419420or add `--type-add=web:*.{html,css,js}` to your ripgrep configuration file.421([Configuration files](#configuration-file) are covered in more detail later.)422423#### The special `all` file type424425A special option supported by the `--type` flag is `all`. `--type all` looks426for a match in any of the supported file types listed by `--type-list`,427including those added on the command line using `--type-add`. It's equivalent428to the command `rg --type agda --type asciidoc --type asm ...`, where `...`429stands for a list of `--type` flags for the rest of the types in `--type-list`.430431As an example, let's suppose you have a shell script in your current directory,432`my-shell-script`, which includes a shell library, `my-shell-library.bash`.433Both `rg --type sh` and `rg --type all` would only search for matches in434`my-shell-library.bash`, not `my-shell-script`, because the globs matched435by the `sh` file type don't include files without an extension. On the436other hand, `rg --type-not all` would search `my-shell-script` but not437`my-shell-library.bash`.438439### Replacements440441ripgrep provides a limited ability to modify its output by replacing matched442text with some other text. This is easiest to explain with an example. Remember443when we searched for the word `fast` in ripgrep's README?444445```446$ rg fast README.md44775: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement44888: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while449119:### Is it really faster than everything else?450124:Summarizing, `ripgrep` is fast because:451129: optimizations to make searching very fast.452```453454What if we wanted to *replace* all occurrences of `fast` with `FAST`? That's455easy with ripgrep's `--replace` flag:456457```458$ rg fast README.md --replace FAST45975: FASTer than both. (N.B. It is not, strictly speaking, a "drop-in" replacement46088: color and full Unicode support. Unlike GNU grep, `ripgrep` stays FAST while461119:### Is it really FASTer than everything else?462124:Summarizing, `ripgrep` is FAST because:463129: optimizations to make searching very FAST.464```465466or, more succinctly,467468```469$ rg fast README.md -r FAST470[snip]471```472473In essence, the `--replace` flag applies *only* to the matching portion of text474in the output. If you instead wanted to replace an entire line of text, then475you need to include the entire line in your match. For example:476477```478$ rg '^.*fast.*$' README.md -r FAST47975:FAST48088:FAST481119:FAST482124:FAST483129:FAST484```485486Alternatively, you can combine the `--only-matching` (or `-o` for short) with487the `--replace` flag to achieve the same result:488489```490$ rg fast README.md --only-matching --replace FAST49175:FAST49288:FAST493119:FAST494124:FAST495129:FAST496```497498or, more succinctly,499500```501$ rg fast README.md -or FAST502[snip]503```504505Finally, replacements can include capturing groups. For example, let's say506we wanted to find all occurrences of `fast` followed by another word and507join them together with a dash. The pattern we might use for that is508`fast\s+(\w+)`, which matches `fast`, followed by any amount of whitespace,509followed by any number of "word" characters. We put the `\w+` in a "capturing510group" (indicated by parentheses) so that we can reference it later in our511replacement string. For example:512513```514$ rg 'fast\s+(\w+)' README.md -r 'fast-$1'51588: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast-while516124:Summarizing, `ripgrep` is fast-because:517```518519Our replacement string here, `fast-$1`, consists of `fast-` followed by the520contents of the capturing group at index `1`. (Capturing groups actually start521at index 0, but the `0`th capturing group always corresponds to the entire522match. The capturing group at index `1` always corresponds to the first523explicit capturing group found in the regex pattern.)524525Capturing groups can also be named, which is sometimes more convenient than526using the indices. For example, the following command is equivalent to the527above command:528529```530$ rg 'fast\s+(?P<word>\w+)' README.md -r 'fast-$word'53188: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast-while532124:Summarizing, `ripgrep` is fast-because:533```534535It is important to note that ripgrep **will never modify your files**. The536`--replace` flag only controls ripgrep's output. (And there is no flag to let537you do a replacement in a file.)538539540### Configuration file541542It is possible that ripgrep's default options aren't suitable in every case.543For that reason, and because shell aliases aren't always convenient, ripgrep544supports configuration files.545546Setting up a configuration file is simple. ripgrep will not look in any547predetermined directory for a config file automatically. Instead, you need to548set the `RIPGREP_CONFIG_PATH` environment variable to the file path of your549config file. Once the environment variable is set, open the file and just type550in the flags you want set automatically. There are only two rules for551describing the format of the config file:5525531. Every line is a shell argument, after trimming whitespace.5542. Lines starting with `#` (optionally preceded by any amount of whitespace)555are ignored.556557In particular, there is no escaping. Each line is given to ripgrep as a single558command line argument verbatim.559560Here's an example of a configuration file, which demonstrates some of the561formatting peculiarities:562563```564$ cat $HOME/.ripgreprc565# Don't let ripgrep vomit really long lines to my terminal, and show a preview.566--max-columns=150567--max-columns-preview568569# Add my 'web' type.570--type-add571web:*.{html,css,js}*572573# Search hidden files / directories (e.g. dotfiles) by default574--hidden575576# Using glob patterns to include/exclude files or folders577--glob=!.git/*578579# or580--glob581!.git/*582583# Set the colors.584--colors=line:none585--colors=line:style:bold586587# Because who cares about case!?588--smart-case589```590591When we use a flag that has a value, we either put the flag and the value on592the same line but delimited by an `=` sign (e.g., `--max-columns=150`), or we593put the flag and the value on two different lines. This is because ripgrep's594argument parser knows to treat the single argument `--max-columns=150` as a595flag with a value, but if we had written `--max-columns 150` in our596configuration file, then ripgrep's argument parser wouldn't know what to do597with it.598599Putting the flag and value on different lines is exactly equivalent and is a600matter of style.601602Comments are encouraged so that you remember what the config is doing. Empty603lines are OK too.604605So let's say you're using the above configuration file, but while you're at a606terminal, you really want to be able to see lines longer than 150 columns. What607do you do? Thankfully, all you need to do is pass `--max-columns 0` (or `-M0`608for short) on the command line, which will override your configuration file's609setting. This works because ripgrep's configuration file is *prepended* to the610explicit arguments you give it on the command line. Since flags given later611override flags given earlier, everything works as expected. This works for most612other flags as well, and each flag's documentation states which other flags613override it.614615If you're confused about what configuration file ripgrep is reading arguments616from, then running ripgrep with the `--debug` flag should help clarify things.617The debug output should note what config file is being loaded and the arguments618that have been read from the configuration.619620Finally, if you want to make absolutely sure that ripgrep *isn't* reading a621configuration file, then you can pass the `--no-config` flag, which will always622prevent ripgrep from reading extraneous configuration from the environment,623regardless of what other methods of configuration are added to ripgrep in the624future.625626627### File encoding628629[Text encoding](https://en.wikipedia.org/wiki/Character_encoding) is a complex630topic, but we can try to summarize its relevancy to ripgrep:631632* Files are generally just a bundle of bytes. There is no reliable way to know633 their encoding.634* Either the encoding of the pattern must match the encoding of the files being635 searched, or a form of transcoding must be performed that converts either the636 pattern or the file to the same encoding as the other.637* ripgrep tends to work best on plain text files, and among plain text files,638 the most popular encodings likely consist of ASCII, latin1 or UTF-8. As639 a special exception, UTF-16 is prevalent in Windows environments640641In light of the above, here is how ripgrep behaves when `--encoding auto` is642given, which is the default:643644* All input is assumed to be ASCII compatible (which means every byte that645 corresponds to an ASCII codepoint actually is an ASCII codepoint). This646 includes ASCII itself, latin1 and UTF-8.647* ripgrep works best with UTF-8. For example, ripgrep's regular expression648 engine supports Unicode features. Namely, character classes like `\w` will649 match all word characters by Unicode's definition and `.` will match any650 Unicode codepoint instead of any byte. These constructions assume UTF-8,651 so they simply won't match when they come across bytes in a file that aren't652 UTF-8.653* To handle the UTF-16 case, ripgrep will do something called "BOM sniffing"654 by default. That is, the first three bytes of a file will be read, and if655 they correspond to a UTF-16 BOM, then ripgrep will transcode the contents of656 the file from UTF-16 to UTF-8, and then execute the search on the transcoded657 version of the file. (This incurs a performance penalty since transcoding658 is needed in addition to regex searching.) If the file contains invalid659 UTF-16, then the Unicode replacement codepoint is substituted in place of660 invalid code units.661* To handle other cases, ripgrep provides a `-E/--encoding` flag, which permits662 you to specify an encoding from the663 [Encoding Standard](https://encoding.spec.whatwg.org/#concept-encoding-get).664 ripgrep will assume *all* files searched are the encoding specified (unless665 the file has a BOM) and will perform a transcoding step just like in the666 UTF-16 case described above.667668By default, ripgrep will not require its input be valid UTF-8. That is, ripgrep669can and will search arbitrary bytes. The key here is that if you're searching670content that isn't UTF-8, then the usefulness of your pattern will degrade. If671you're searching bytes that aren't ASCII compatible, then it's likely the672pattern won't find anything. With all that said, this mode of operation is673important, because it lets you find ASCII or UTF-8 *within* files that are674otherwise arbitrary bytes.675676As a special case, the `-E/--encoding` flag supports the value `none`, which677will completely disable all encoding related logic, including BOM sniffing.678When `-E/--encoding` is set to `none`, ripgrep will search the raw bytes of679the underlying file with no transcoding step. For example, here's how you might680search the raw UTF-16 encoding of the string `Шерлок`:681682```683$ rg '(?-u)\(\x045\x04@\x04;\x04>\x04:\x04' -E none -a some-utf16-file684```685686Of course, that's just an example meant to show how one can drop down into687raw bytes. Namely, the simpler command works as you might expect automatically:688689```690$ rg 'Шерлок' some-utf16-file691```692693Finally, it is possible to disable ripgrep's Unicode support from within the694regular expression. For example, let's say you wanted `.` to match any byte695rather than any Unicode codepoint. (You might want this while searching a696binary file, since `.` by default will not match invalid UTF-8.) You could do697this by disabling Unicode via a regular expression flag:698699```700$ rg '(?-u:.)'701```702703This works for any part of the pattern. For example, the following will find704any Unicode word character followed by any ASCII word character followed by705another Unicode word character:706707```708$ rg '\w(?-u:\w)\w'709```710711712### Binary data713714In addition to skipping hidden files and files in your `.gitignore` by default,715ripgrep also attempts to skip binary files. ripgrep does this by default716because binary files (like PDFs or images) are typically not things you want to717search when searching for regex matches. Moreover, if content in a binary file718did match, then it's possible for undesirable binary data to be printed to your719terminal and wreak havoc.720721Unfortunately, unlike skipping hidden files and respecting your `.gitignore`722rules, a file cannot as easily be classified as binary. In order to figure out723whether a file is binary, the most effective heuristic that balances724correctness with performance is to simply look for `NUL` bytes. At that point,725the determination is simple: a file is considered "binary" if and only if it726contains a `NUL` byte somewhere in its contents.727728The issue is that while most binary files will have a `NUL` byte toward the729beginning of its contents, this is not necessarily true. The `NUL` byte might730be the very last byte in a large file, but that file is still considered731binary. While this leads to a fair amount of complexity inside ripgrep's732implementation, it also results in some unintuitive user experiences.733734At a high level, ripgrep operates in three different modes with respect to735binary files:7367371. The default mode is to attempt to remove binary files from a search738 completely. This is meant to mirror how ripgrep removes hidden files and739 files in your `.gitignore` automatically. That is, as soon as a file is740 detected as binary, searching stops. If a match was already printed (because741 it was detected long before a `NUL` byte), then ripgrep will print a warning742 message indicating that the search stopped prematurely. This default mode743 **only applies to files searched by ripgrep as a result of recursive744 directory traversal**, which is consistent with ripgrep's other automatic745 filtering. For example, `rg foo .file` will search `.file` even though it746 is hidden. Similarly, `rg foo binary-file` will search `binary-file` in747 "binary" mode automatically.7482. Binary mode is similar to the default mode, except it will not always749 stop searching after it sees a `NUL` byte. Namely, in this mode, ripgrep750 will continue searching a file that is known to be binary until the first751 of two conditions is met: 1) the end of the file has been reached or 2) a752 match is or has been seen. This means that in binary mode, if ripgrep753 reports no matches, then there are no matches in the file. When a match does754 occur, ripgrep prints a message similar to one it prints when in its default755 mode indicating that the search has stopped prematurely. This mode can be756 forcefully enabled for all files with the `--binary` flag. The purpose of757 binary mode is to provide a way to discover matches in all files, but to758 avoid having binary data dumped into your terminal.7593. Text mode completely disables all binary detection and searches all files760 as if they were text. This is useful when searching a file that is761 predominantly text but contains a `NUL` byte, or if you are specifically762 trying to search binary data. This mode can be enabled with the `-a/--text`763 flag. Note that when using this mode on very large binary files, it is764 possible for ripgrep to use a lot of memory.765766Unfortunately, there is one additional complexity in ripgrep that can make it767difficult to reason about binary files. That is, the way binary detection works768depends on the way that ripgrep searches your files. Specifically:769770* When ripgrep uses memory maps, then binary detection is only performed on the771 first few kilobytes of the file in addition to every matching line.772* When ripgrep doesn't use memory maps, then binary detection is performed on773 all bytes searched.774775This means that whether a file is detected as binary or not can change based776on the internal search strategy used by ripgrep. If you prefer to keep777ripgrep's binary file detection consistent, then you can disable memory maps778via the `--no-mmap` flag. (The cost will be a small performance regression when779searching very large files on some platforms.)780781782### Preprocessor783784In ripgrep, a preprocessor is any type of command that can be run to transform785the input of every file before ripgrep searches it. This makes it possible to786search virtually any kind of content that can be automatically converted to787text without having to teach ripgrep how to read said content.788789One common example is searching PDFs. PDFs are first and foremost meant to be790displayed to users. But PDFs often have text streams in them that can be useful791to search. In our case, we want to search Bruce Watson's excellent792dissertation,793[Taxonomies and Toolkits of Regular Language Algorithms](https://burntsushi.net/stuff/1995-watson.pdf).794After downloading it, let's try searching it:795796```797$ rg 'The Commentz-Walter algorithm' 1995-watson.pdf798$799```800801Surely, a dissertation on regular language algorithms would mention802Commentz-Walter. Indeed it does, but our search isn't picking it up because803PDFs are a binary format, and the text shown in the PDF may not be encoded as804simple contiguous UTF-8. Namely, even passing the `-a/--text` flag to ripgrep805will not make our search work.806807One way to fix this is to convert the PDF to plain text first. This won't work808well for all PDFs, but does great in a lot of cases. (Note that the tool we809use, `pdftotext`, is part of the [poppler](https://poppler.freedesktop.org)810PDF rendering library.)811812```813$ pdftotext 1995-watson.pdf > 1995-watson.txt814$ rg 'The Commentz-Walter algorithm' 1995-watson.txt815316:The Commentz-Walter algorithms : : : : : : : : : : : : : : :8167165:4.4 The Commentz-Walter algorithms81710062:in input string S , we obtain the Boyer-Moore algorithm. The Commentz-Walter algorithm81817218:The Commentz-Walter algorithm (and its variants) displayed more interesting behaviour,81917249:Aho-Corasick algorithms are used extensively. The Commentz-Walter algorithms are used82017297: The Commentz-Walter algorithms (CW). In all versions of the CW algorithms, a common program skeleton is used with di erent shift functions. The CW algorithms are821```822823But having to explicitly convert every file can be a pain, especially when you824have a directory full of PDF files. Instead, we can use ripgrep's preprocessor825feature to search the PDF. ripgrep's `--pre` flag works by taking a single826command name and then executing that command for every file that it searches.827ripgrep passes the file path as the first and only argument to the command and828also sends the contents of the file to stdin. So let's write a simple shell829script that wraps `pdftotext` in a way that conforms to this interface:830831```832$ cat preprocess833#!/bin/sh834835exec pdftotext - -836```837838With `preprocess` in the same directory as `1995-watson.pdf`, we can now use it839to search the PDF:840841```842$ rg --pre ./preprocess 'The Commentz-Walter algorithm' 1995-watson.pdf843316:The Commentz-Walter algorithms : : : : : : : : : : : : : : :8447165:4.4 The Commentz-Walter algorithms84510062:in input string S , we obtain the Boyer-Moore algorithm. The Commentz-Walter algorithm84617218:The Commentz-Walter algorithm (and its variants) displayed more interesting behaviour,84717249:Aho-Corasick algorithms are used extensively. The Commentz-Walter algorithms are used84817297: The Commentz-Walter algorithms (CW). In all versions of the CW algorithms, a common program skeleton is used with di erent shift functions. The CW algorithms are849```850851Note that `preprocess` must be resolvable to a command that ripgrep can read.852The simplest way to do this is to put your preprocessor command in a directory853that is in your `PATH` (or equivalent), or otherwise use an absolute path.854855As a bonus, this turns out to be quite a bit faster than other specialized PDF856grepping tools:857858```859$ time rg --pre ./preprocess 'The Commentz-Walter algorithm' 1995-watson.pdf -c8606861862real 0.697863user 0.684864sys 0.007865maxmem 16 MB866faults 0867868$ time pdfgrep 'The Commentz-Walter algorithm' 1995-watson.pdf -c8696870871real 1.336872user 1.310873sys 0.023874maxmem 16 MB875faults 0876```877878If you wind up needing to search a lot of PDFs, then ripgrep's parallelism can879make the speed difference even greater.880881#### A more robust preprocessor882883One of the problems with the aforementioned preprocessor is that it will fail884if you try to search a file that isn't a PDF:885886```887$ echo foo > not-a-pdf888$ rg --pre ./preprocess 'The Commentz-Walter algorithm' not-a-pdf889not-a-pdf: preprocessor command failed: '"./preprocess" "not-a-pdf"':890-------------------------------------------------------------------------------891Syntax Warning: May not be a PDF file (continuing anyway)892Syntax Error: Couldn't find trailer dictionary893Syntax Error: Couldn't find trailer dictionary894Syntax Error: Couldn't read xref table895```896897To fix this, we can make our preprocessor script a bit more robust by only898running `pdftotext` when we think the input is a non-empty PDF:899900```901$ cat preprocessor902#!/bin/sh903904case "$1" in905*.pdf)906 # The -s flag ensures that the file is non-empty.907 if [ -s "$1" ]; then908 exec pdftotext - -909 else910 exec cat911 fi912 ;;913*)914 exec cat915 ;;916esac917```918919We can even extend our preprocessor to search other kinds of files. Sometimes920we don't always know the file type from the file name, so we can use the `file`921utility to "sniff" the type of the file based on its contents:922923```924$ cat processor925#!/bin/sh926927case "$1" in928*.pdf)929 # The -s flag ensures that the file is non-empty.930 if [ -s "$1" ]; then931 exec pdftotext - -932 else933 exec cat934 fi935 ;;936*)937 case $(file "$1") in938 *Zstandard*)939 exec pzstd -cdq940 ;;941 *)942 exec cat943 ;;944 esac945 ;;946esac947```948949#### Reducing preprocessor overhead950951There is one more problem with the above approach: it requires running a952preprocessor for every single file that ripgrep searches. If every file needs953a preprocessor, then this is OK. But if most don't, then this can substantially954slow down searches because of the overhead of launching new processors. You955can avoid this by telling ripgrep to only invoke the preprocessor when the file956path matches a glob. For example, consider the performance difference even when957searching a repository as small as ripgrep's:958959```960$ time rg --pre pre-rg 'fn is_empty' -c961crates/globset/src/lib.rs:1962crates/matcher/src/lib.rs:2963crates/ignore/src/overrides.rs:1964crates/ignore/src/gitignore.rs:1965crates/ignore/src/types.rs:1966967real 0.138968user 0.485969sys 0.209970maxmem 7 MB971faults 0972973$ time rg --pre pre-rg --pre-glob '*.pdf' 'fn is_empty' -c974crates/globset/src/lib.rs:1975crates/ignore/src/types.rs:1976crates/ignore/src/gitignore.rs:1977crates/ignore/src/overrides.rs:1978crates/matcher/src/lib.rs:2979980real 0.008981user 0.010982sys 0.002983maxmem 7 MB984faults 0985```986987988### Common options989990ripgrep has a lot of flags. Too many to keep in your head at once. This section991is intended to give you a sampling of some of the most important and frequently992used options that will likely impact how you use ripgrep on a regular basis.993994* `-h`: Show ripgrep's condensed help output.995* `--help`: Show ripgrep's longer form help output. (Nearly what you'd find in996 ripgrep's man page, so pipe it into a pager!)997* `-i/--ignore-case`: When searching for a pattern, ignore case differences.998 That is `rg -i fast` matches `fast`, `fASt`, `FAST`, etc.999* `-S/--smart-case`: This is similar to `--ignore-case`, but disables itself1000 if the pattern contains any uppercase letters. Usually this flag is put into1001 alias or a config file.1002* `-F/--fixed-strings`: Disable regular expression matching and treat the pattern1003 as a literal string.1004* `-w/--word-regexp`: Require that all matches of the pattern be surrounded1005 by word boundaries. That is, given `pattern`, the `--word-regexp` flag will1006 cause ripgrep to behave as if `pattern` were actually1007 `\b{start-half}(?:pattern)\b{end-half}`.1008 (Unlike `\b`, these half-boundaries don't require a word character on one1009 side. For example, `rg -w -e -2` will match `-2` in `(-2)` but `rg '\b-2\b'`1010 will not.)1011* `-c/--count`: Report a count of total matched lines.1012* `--files`: Print the files that ripgrep *would* search, but don't actually1013 search them.1014* `-a/--text`: Search binary files as if they were plain text.1015* `-U/--multiline`: Permit matches to span multiple lines.1016* `-z/--search-zip`: Search compressed files (gzip, bzip2, lzma, xz, lz4,1017 brotli, zstd). This is disabled by default.1018* `-C/--context`: Show the lines surrounding a match.1019* `--sort path`: Force ripgrep to sort its output by file name. (This disables1020 parallelism, so it might be slower.)1021* `-L/--follow`: Follow symbolic links while recursively searching.1022* `-M/--max-columns`: Limit the length of lines printed by ripgrep.1023* `--debug`: Shows ripgrep's debug output. This is useful for understanding1024 why a particular file might be ignored from search, or what kinds of1025 configuration ripgrep is loading from the environment.