PageRenderTime 222ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/GUIDE.md

https://github.com/BurntSushi/ripgrep
Markdown | 1008 lines | 809 code | 199 blank | 0 comment | 0 complexity | 628c840f16bd468a31fca49755fe30dc MD5 | raw file
Possible License(s): MIT, Unlicense
  1. ## User Guide
  2. This guide is intended to give an elementary description of ripgrep and an
  3. overview of its capabilities. This guide assumes that ripgrep is
  4. [installed](README.md#installation)
  5. and that readers have passing familiarity with using command line tools. This
  6. also assumes a Unix-like system, although most commands are probably easily
  7. translatable to any command line shell environment.
  8. ### Table of Contents
  9. * [Basics](#basics)
  10. * [Recursive search](#recursive-search)
  11. * [Automatic filtering](#automatic-filtering)
  12. * [Manual filtering: globs](#manual-filtering-globs)
  13. * [Manual filtering: file types](#manual-filtering-file-types)
  14. * [Replacements](#replacements)
  15. * [Configuration file](#configuration-file)
  16. * [File encoding](#file-encoding)
  17. * [Binary data](#binary-data)
  18. * [Preprocessor](#preprocessor)
  19. * [Common options](#common-options)
  20. ### Basics
  21. ripgrep is a command line tool that searches your files for patterns that
  22. you give it. ripgrep behaves as if reading each file line by line. If a line
  23. matches the pattern provided to ripgrep, then that line will be printed. If a
  24. line does not match the pattern, then the line is not printed.
  25. The best way to see how this works is with an example. To show an example, we
  26. need something to search. Let's try searching ripgrep's source code. First
  27. grab a ripgrep source archive from
  28. https://github.com/BurntSushi/ripgrep/archive/0.7.1.zip
  29. and extract it:
  30. ```
  31. $ curl -LO https://github.com/BurntSushi/ripgrep/archive/0.7.1.zip
  32. $ unzip 0.7.1.zip
  33. $ cd ripgrep-0.7.1
  34. $ ls
  35. benchsuite grep tests Cargo.toml LICENSE-MIT
  36. ci ignore wincolor CHANGELOG.md README.md
  37. complete pkg appveyor.yml compile snapcraft.yaml
  38. doc src build.rs COPYING UNLICENSE
  39. globset termcolor Cargo.lock HomebrewFormula
  40. ```
  41. Let's try our first search by looking for all occurrences of the word `fast`
  42. in `README.md`:
  43. ```
  44. $ rg fast README.md
  45. 75: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement
  46. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while
  47. 119:### Is it really faster than everything else?
  48. 124:Summarizing, `ripgrep` is fast because:
  49. 129: optimizations to make searching very fast.
  50. ```
  51. (**Note:** If you see an error message from ripgrep saying that it didn't
  52. search any files, then re-run ripgrep with the `--debug` flag. One likely cause
  53. of this is that you have a `*` rule in a `$HOME/.gitignore` file.)
  54. So what happened here? ripgrep read the contents of `README.md`, and for each
  55. line that contained `fast`, ripgrep printed it to your terminal. ripgrep also
  56. included the line number for each line by default. If your terminal supports
  57. colors, then your output might actually look something like this screenshot:
  58. [![A screenshot of a sample search ripgrep](https://burntsushi.net/stuff/ripgrep-guide-sample.png)](https://burntsushi.net/stuff/ripgrep-guide-sample.png)
  59. In this example, we searched for something called a "literal" string. This
  60. means that our pattern was just some normal text that we asked ripgrep to
  61. find. But ripgrep supports the ability to specify patterns via [regular
  62. expressions](https://en.wikipedia.org/wiki/Regular_expression). As an example,
  63. what if we wanted to find all lines have a word that contains `fast` followed
  64. by some number of other letters?
  65. ```
  66. $ rg 'fast\w+' README.md
  67. 75: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement
  68. 119:### Is it really faster than everything else?
  69. ```
  70. In this example, we used the pattern `fast\w+`. This pattern tells ripgrep to
  71. look for any lines containing the letters `fast` followed by *one or more*
  72. word-like characters. Namely, `\w` matches characters that compose words (like
  73. `a` and `L` but unlike `.` and ` `). The `+` after the `\w` means, "match the
  74. previous pattern one or more times." This means that the word `fast` won't
  75. match because there are no word characters following the final `t`. But a word
  76. like `faster` will. `faste` would also match!
  77. Here's a different variation on this same theme:
  78. ```
  79. $ rg 'fast\w*' README.md
  80. 75: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement
  81. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while
  82. 119:### Is it really faster than everything else?
  83. 124:Summarizing, `ripgrep` is fast because:
  84. 129: optimizations to make searching very fast.
  85. ```
  86. In this case, we used `fast\w*` for our pattern instead of `fast\w+`. The `*`
  87. means that it should match *zero* or more times. In this case, ripgrep will
  88. print the same lines as the pattern `fast`, but if your terminal supports
  89. colors, you'll notice that `faster` will be highlighted instead of just the
  90. `fast` prefix.
  91. It is beyond the scope of this guide to provide a full tutorial on regular
  92. expressions, but ripgrep's specific syntax is documented here:
  93. https://docs.rs/regex/*/regex/#syntax
  94. ### Recursive search
  95. In the previous section, we showed how to use ripgrep to search a single file.
  96. In this section, we'll show how to use ripgrep to search an entire directory
  97. of files. In fact, *recursively* searching your current working directory is
  98. the default mode of operation for ripgrep, which means doing this is very
  99. simple.
  100. Using our unzipped archive of ripgrep source code, here's how to find all
  101. function definitions whose name is `write`:
  102. ```
  103. $ rg 'fn write\('
  104. src/printer.rs
  105. 469: fn write(&mut self, buf: &[u8]) {
  106. termcolor/src/lib.rs
  107. 227: fn write(&mut self, b: &[u8]) -> io::Result<usize> {
  108. 250: fn write(&mut self, b: &[u8]) -> io::Result<usize> {
  109. 428: fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) }
  110. 441: fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) }
  111. 454: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  112. 511: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  113. 848: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  114. 915: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  115. 949: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  116. 1114: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  117. 1348: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  118. 1353: fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  119. ```
  120. (**Note:** We escape the `(` here because `(` has special significance inside
  121. regular expressions. You could also use `rg -F 'fn write('` to achieve the
  122. same thing, where `-F` interprets your pattern as a literal string instead of
  123. a regular expression.)
  124. In this example, we didn't specify a file at all. Instead, ripgrep defaulted
  125. to searching your current directory in the absence of a path. In general,
  126. `rg foo` is equivalent to `rg foo ./`.
  127. This particular search showed us results in both the `src` and `termcolor`
  128. directories. The `src` directory is the core ripgrep code where as `termcolor`
  129. is a dependency of ripgrep (and is used by other tools). What if we only wanted
  130. to search core ripgrep code? Well, that's easy, just specify the directory you
  131. want:
  132. ```
  133. $ rg 'fn write\(' src
  134. src/printer.rs
  135. 469: fn write(&mut self, buf: &[u8]) {
  136. ```
  137. Here, ripgrep limited its search to the `src` directory. Another way of doing
  138. this search would be to `cd` into the `src` directory and simply use `rg 'fn
  139. write\('` again.
  140. ### Automatic filtering
  141. After recursive search, ripgrep's most important feature is what it *doesn't*
  142. search. By default, when you search a directory, ripgrep will ignore all of
  143. the following:
  144. 1. Files and directories that match the rules in your `.gitignore` glob
  145. pattern.
  146. 2. Hidden files and directories.
  147. 3. Binary files. (ripgrep considers any file with a `NUL` byte to be binary.)
  148. 4. Symbolic links aren't followed.
  149. All of these things can be toggled using various flags provided by ripgrep:
  150. 1. You can disable `.gitignore` handling with the `--no-ignore` flag.
  151. 2. Hidden files and directories can be searched with the `--hidden` flag.
  152. 3. Binary files can be searched via the `--text` (`-a` for short) flag.
  153. Be careful with this flag! Binary files may emit control characters to your
  154. terminal, which might cause strange behavior.
  155. 4. ripgrep can follow symlinks with the `--follow` (`-L` for short) flag.
  156. As a special convenience, ripgrep also provides a flag called `--unrestricted`
  157. (`-u` for short). Repeated uses of this flag will cause ripgrep to disable
  158. more and more of its filtering. That is, `-u` will disable `.gitignore`
  159. handling, `-uu` will search hidden files and directories and `-uuu` will search
  160. binary files. This is useful when you're using ripgrep and you aren't sure
  161. whether its filtering is hiding results from you. Tacking on a couple `-u`
  162. flags is a quick way to find out. (Use the `--debug` flag if you're still
  163. perplexed, and if that doesn't help,
  164. [file an issue](https://github.com/BurntSushi/ripgrep/issues/new).)
  165. ripgrep's `.gitignore` handling actually goes a bit beyond just `.gitignore`
  166. files. ripgrep will also respect repository specific rules found in
  167. `$GIT_DIR/info/exclude`, as well as any global ignore rules in your
  168. `core.excludesFile` (which is usually `$XDG_CONFIG_HOME/git/ignore` on
  169. Unix-like systems).
  170. Sometimes you want to search files that are in your `.gitignore`, so it is
  171. possible to specify additional ignore rules or overrides in a `.ignore`
  172. (application agnostic) or `.rgignore` (ripgrep specific) file.
  173. For example, let's say you have a `.gitignore` file that looks like this:
  174. ```
  175. log/
  176. ```
  177. This generally means that any `log` directory won't be tracked by `git`.
  178. However, perhaps it contains useful output that you'd like to include in your
  179. searches, but you still don't want to track it in `git`. You can achieve this
  180. by creating a `.ignore` file in the same directory as the `.gitignore` file
  181. with the following contents:
  182. ```
  183. !log/
  184. ```
  185. ripgrep treats `.ignore` files with higher precedence than `.gitignore` files
  186. (and treats `.rgignore` files with higher precedence than `.ignore` files).
  187. This means ripgrep will see the `!log/` whitelist rule first and search that
  188. directory.
  189. Like `.gitignore`, a `.ignore` file can be placed in any directory. Its rules
  190. will be processed with respect to the directory it resides in, just like
  191. `.gitignore`.
  192. To process `.gitignore` and `.ignore` files case insensitively, use the flag
  193. `--ignore-file-case-insensitive`. This is especially useful on case insensitive
  194. file systems like those on Windows and macOS. Note though that this can come
  195. with a significant performance penalty, and is therefore disabled by default.
  196. For a more in depth description of how glob patterns in a `.gitignore` file
  197. are interpreted, please see `man gitignore`.
  198. ### Manual filtering: globs
  199. In the previous section, we talked about ripgrep's filtering that it does by
  200. default. It is "automatic" because it reacts to your environment. That is, it
  201. uses already existing `.gitignore` files to produce more relevant search
  202. results.
  203. In addition to automatic filtering, ripgrep also provides more manual or ad hoc
  204. filtering. This comes in two varieties: additional glob patterns specified in
  205. your ripgrep commands and file type filtering. This section covers glob
  206. patterns while the next section covers file type filtering.
  207. In our ripgrep source code (see [Basics](#basics) for instructions on how to
  208. get a source archive to search), let's say we wanted to see which things depend
  209. on `clap`, our argument parser.
  210. We could do this:
  211. ```
  212. $ rg clap
  213. [lots of results]
  214. ```
  215. But this shows us many things, and we're only interested in where we wrote
  216. `clap` as a dependency. Instead, we could limit ourselves to TOML files, which
  217. is how dependencies are communicated to Rust's build tool, Cargo:
  218. ```
  219. $ rg clap -g '*.toml'
  220. Cargo.toml
  221. 35:clap = "2.26"
  222. 51:clap = "2.26"
  223. ```
  224. The `-g '*.toml'` syntax says, "make sure every file searched matches this
  225. glob pattern." Note that we put `'*.toml'` in single quotes to prevent our
  226. shell from expanding the `*`.
  227. If we wanted, we could tell ripgrep to search anything *but* `*.toml` files:
  228. ```
  229. $ rg clap -g '!*.toml'
  230. [lots of results]
  231. ```
  232. This will give you a lot of results again as above, but they won't include
  233. files ending with `.toml`. Note that the use of a `!` here to mean "negation"
  234. is a bit non-standard, but it was chosen to be consistent with how globs in
  235. `.gitignore` files are written. (Although, the meaning is reversed. In
  236. `.gitignore` files, a `!` prefix means whitelist, and on the command line, a
  237. `!` means blacklist.)
  238. Globs are interpreted in exactly the same way as `.gitignore` patterns. That
  239. is, later globs will override earlier globs. For example, the following command
  240. will search only `*.toml` files:
  241. ```
  242. $ rg clap -g '!*.toml' -g '*.toml'
  243. ```
  244. Interestingly, reversing the order of the globs in this case will match
  245. nothing, since the presence of at least one non-blacklist glob will institute a
  246. requirement that every file searched must match at least one glob. In this
  247. case, the blacklist glob takes precedence over the previous glob and prevents
  248. any file from being searched at all!
  249. ### Manual filtering: file types
  250. Over time, you might notice that you use the same glob patterns over and over.
  251. For example, you might find yourself doing a lot of searches where you only
  252. want to see results for Rust files:
  253. ```
  254. $ rg 'fn run' -g '*.rs'
  255. ```
  256. Instead of writing out the glob every time, you can use ripgrep's support for
  257. file types:
  258. ```
  259. $ rg 'fn run' --type rust
  260. ```
  261. or, more succinctly,
  262. ```
  263. $ rg 'fn run' -trust
  264. ```
  265. The way the `--type` flag functions is simple. It acts as a name that is
  266. assigned to one or more globs that match the relevant files. This lets you
  267. write a single type that might encompass a broad range of file extensions. For
  268. example, if you wanted to search C files, you'd have to check both C source
  269. files and C header files:
  270. ```
  271. $ rg 'int main' -g '*.{c,h}'
  272. ```
  273. or you could just use the C file type:
  274. ```
  275. $ rg 'int main' -tc
  276. ```
  277. Just as you can write blacklist globs, you can blacklist file types too:
  278. ```
  279. $ rg clap --type-not rust
  280. ```
  281. or, more succinctly,
  282. ```
  283. $ rg clap -Trust
  284. ```
  285. That is, `-t` means "include files of this type" where as `-T` means "exclude
  286. files of this type."
  287. To see the globs that make up a type, run `rg --type-list`:
  288. ```
  289. $ rg --type-list | rg '^make:'
  290. make: *.mak, *.mk, GNUmakefile, Gnumakefile, Makefile, gnumakefile, makefile
  291. ```
  292. By default, ripgrep comes with a bunch of pre-defined types. Generally, these
  293. types correspond to well known public formats. But you can define your own
  294. types as well. For example, perhaps you frequently search "web" files, which
  295. consist of Javascript, HTML and CSS:
  296. ```
  297. $ rg --type-add 'web:*.html' --type-add 'web:*.css' --type-add 'web:*.js' -tweb title
  298. ```
  299. or, more succinctly,
  300. ```
  301. $ rg --type-add 'web:*.{html,css,js}' -tweb title
  302. ```
  303. The above command defines a new type, `web`, corresponding to the glob
  304. `*.{html,css,js}`. It then applies the new filter with `-tweb` and searches for
  305. the pattern `title`. If you ran
  306. ```
  307. $ rg --type-add 'web:*.{html,css,js}' --type-list
  308. ```
  309. Then you would see your `web` type show up in the list, even though it is not
  310. part of ripgrep's built-in types.
  311. It is important to stress here that the `--type-add` flag only applies to the
  312. current command. It does not add a new file type and save it somewhere in a
  313. persistent form. If you want a type to be available in every ripgrep command,
  314. then you should either create a shell alias:
  315. ```
  316. alias rg="rg --type-add 'web:*.{html,css,js}'"
  317. ```
  318. or add `--type-add=web:*.{html,css,js}` to your ripgrep configuration file.
  319. ([Configuration files](#configuration-file) are covered in more detail later.)
  320. #### The special `all` file type
  321. A special option supported by the `--type` flag is `all`. `--type all` looks
  322. for a match in any of the supported file types listed by `--type-list`,
  323. including those added on the command line using `--type-add`. It's equivalent
  324. to the command `rg --type agda --type asciidoc --type asm ...`, where `...`
  325. stands for a list of `--type` flags for the rest of the types in `--type-list`.
  326. As an example, let's suppose you have a shell script in your current directory,
  327. `my-shell-script`, which includes a shell library, `my-shell-library.bash`.
  328. Both `rg --type sh` and `rg --type all` would only search for matches in
  329. `my-shell-library.bash`, not `my-shell-script`, because the globs matched
  330. by the `sh` file type don't include files without an extension. On the
  331. other hand, `rg --type-not all` would search `my-shell-script` but not
  332. `my-shell-library.bash`.
  333. ### Replacements
  334. ripgrep provides a limited ability to modify its output by replacing matched
  335. text with some other text. This is easiest to explain with an example. Remember
  336. when we searched for the word `fast` in ripgrep's README?
  337. ```
  338. $ rg fast README.md
  339. 75: faster than both. (N.B. It is not, strictly speaking, a "drop-in" replacement
  340. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast while
  341. 119:### Is it really faster than everything else?
  342. 124:Summarizing, `ripgrep` is fast because:
  343. 129: optimizations to make searching very fast.
  344. ```
  345. What if we wanted to *replace* all occurrences of `fast` with `FAST`? That's
  346. easy with ripgrep's `--replace` flag:
  347. ```
  348. $ rg fast README.md --replace FAST
  349. 75: FASTer than both. (N.B. It is not, strictly speaking, a "drop-in" replacement
  350. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays FAST while
  351. 119:### Is it really FASTer than everything else?
  352. 124:Summarizing, `ripgrep` is FAST because:
  353. 129: optimizations to make searching very FAST.
  354. ```
  355. or, more succinctly,
  356. ```
  357. $ rg fast README.md -r FAST
  358. [snip]
  359. ```
  360. In essence, the `--replace` flag applies *only* to the matching portion of text
  361. in the output. If you instead wanted to replace an entire line of text, then
  362. you need to include the entire line in your match. For example:
  363. ```
  364. $ rg '^.*fast.*$' README.md -r FAST
  365. 75:FAST
  366. 88:FAST
  367. 119:FAST
  368. 124:FAST
  369. 129:FAST
  370. ```
  371. Alternatively, you can combine the `--only-matching` (or `-o` for short) with
  372. the `--replace` flag to achieve the same result:
  373. ```
  374. $ rg fast README.md --only-matching --replace FAST
  375. 75:FAST
  376. 88:FAST
  377. 119:FAST
  378. 124:FAST
  379. 129:FAST
  380. ```
  381. or, more succinctly,
  382. ```
  383. $ rg fast README.md -or FAST
  384. [snip]
  385. ```
  386. Finally, replacements can include capturing groups. For example, let's say
  387. we wanted to find all occurrences of `fast` followed by another word and
  388. join them together with a dash. The pattern we might use for that is
  389. `fast\s+(\w+)`, which matches `fast`, followed by any amount of whitespace,
  390. followed by any number of "word" characters. We put the `\w+` in a "capturing
  391. group" (indicated by parentheses) so that we can reference it later in our
  392. replacement string. For example:
  393. ```
  394. $ rg 'fast\s+(\w+)' README.md -r 'fast-$1'
  395. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast-while
  396. 124:Summarizing, `ripgrep` is fast-because:
  397. ```
  398. Our replacement string here, `fast-$1`, consists of `fast-` followed by the
  399. contents of the capturing group at index `1`. (Capturing groups actually start
  400. at index 0, but the `0`th capturing group always corresponds to the entire
  401. match. The capturing group at index `1` always corresponds to the first
  402. explicit capturing group found in the regex pattern.)
  403. Capturing groups can also be named, which is sometimes more convenient than
  404. using the indices. For example, the following command is equivalent to the
  405. above command:
  406. ```
  407. $ rg 'fast\s+(?P<word>\w+)' README.md -r 'fast-$word'
  408. 88: color and full Unicode support. Unlike GNU grep, `ripgrep` stays fast-while
  409. 124:Summarizing, `ripgrep` is fast-because:
  410. ```
  411. It is important to note that ripgrep **will never modify your files**. The
  412. `--replace` flag only controls ripgrep's output. (And there is no flag to let
  413. you do a replacement in a file.)
  414. ### Configuration file
  415. It is possible that ripgrep's default options aren't suitable in every case.
  416. For that reason, and because shell aliases aren't always convenient, ripgrep
  417. supports configuration files.
  418. Setting up a configuration file is simple. ripgrep will not look in any
  419. predetermined directory for a config file automatically. Instead, you need to
  420. set the `RIPGREP_CONFIG_PATH` environment variable to the file path of your
  421. config file. Once the environment variable is set, open the file and just type
  422. in the flags you want set automatically. There are only two rules for
  423. describing the format of the config file:
  424. 1. Every line is a shell argument, after trimming whitespace.
  425. 2. Lines starting with `#` (optionally preceded by any amount of whitespace)
  426. are ignored.
  427. In particular, there is no escaping. Each line is given to ripgrep as a single
  428. command line argument verbatim.
  429. Here's an example of a configuration file, which demonstrates some of the
  430. formatting peculiarities:
  431. ```
  432. $ cat $HOME/.ripgreprc
  433. # Don't let ripgrep vomit really long lines to my terminal, and show a preview.
  434. --max-columns=150
  435. --max-columns-preview
  436. # Add my 'web' type.
  437. --type-add
  438. web:*.{html,css,js}*
  439. # Using glob patterns to include/exclude files or folders
  440. --glob=!git/*
  441. # or
  442. --glob
  443. !git/*
  444. # Set the colors.
  445. --colors=line:none
  446. --colors=line:style:bold
  447. # Because who cares about case!?
  448. --smart-case
  449. ```
  450. When we use a flag that has a value, we either put the flag and the value on
  451. the same line but delimited by an `=` sign (e.g., `--max-columns=150`), or we
  452. put the flag and the value on two different lines. This is because ripgrep's
  453. argument parser knows to treat the single argument `--max-columns=150` as a
  454. flag with a value, but if we had written `--max-columns 150` in our
  455. configuration file, then ripgrep's argument parser wouldn't know what to do
  456. with it.
  457. Putting the flag and value on different lines is exactly equivalent and is a
  458. matter of style.
  459. Comments are encouraged so that you remember what the config is doing. Empty
  460. lines are OK too.
  461. So let's say you're using the above configuration file, but while you're at a
  462. terminal, you really want to be able to see lines longer than 150 columns. What
  463. do you do? Thankfully, all you need to do is pass `--max-columns 0` (or `-M0`
  464. for short) on the command line, which will override your configuration file's
  465. setting. This works because ripgrep's configuration file is *prepended* to the
  466. explicit arguments you give it on the command line. Since flags given later
  467. override flags given earlier, everything works as expected. This works for most
  468. other flags as well, and each flag's documentation states which other flags
  469. override it.
  470. If you're confused about what configuration file ripgrep is reading arguments
  471. from, then running ripgrep with the `--debug` flag should help clarify things.
  472. The debug output should note what config file is being loaded and the arguments
  473. that have been read from the configuration.
  474. Finally, if you want to make absolutely sure that ripgrep *isn't* reading a
  475. configuration file, then you can pass the `--no-config` flag, which will always
  476. prevent ripgrep from reading extraneous configuration from the environment,
  477. regardless of what other methods of configuration are added to ripgrep in the
  478. future.
  479. ### File encoding
  480. [Text encoding](https://en.wikipedia.org/wiki/Character_encoding) is a complex
  481. topic, but we can try to summarize its relevancy to ripgrep:
  482. * Files are generally just a bundle of bytes. There is no reliable way to know
  483. their encoding.
  484. * Either the encoding of the pattern must match the encoding of the files being
  485. searched, or a form of transcoding must be performed that converts either the
  486. pattern or the file to the same encoding as the other.
  487. * ripgrep tends to work best on plain text files, and among plain text files,
  488. the most popular encodings likely consist of ASCII, latin1 or UTF-8. As
  489. a special exception, UTF-16 is prevalent in Windows environments
  490. In light of the above, here is how ripgrep behaves when `--encoding auto` is
  491. given, which is the default:
  492. * All input is assumed to be ASCII compatible (which means every byte that
  493. corresponds to an ASCII codepoint actually is an ASCII codepoint). This
  494. includes ASCII itself, latin1 and UTF-8.
  495. * ripgrep works best with UTF-8. For example, ripgrep's regular expression
  496. engine supports Unicode features. Namely, character classes like `\w` will
  497. match all word characters by Unicode's definition and `.` will match any
  498. Unicode codepoint instead of any byte. These constructions assume UTF-8,
  499. so they simply won't match when they come across bytes in a file that aren't
  500. UTF-8.
  501. * To handle the UTF-16 case, ripgrep will do something called "BOM sniffing"
  502. by default. That is, the first three bytes of a file will be read, and if
  503. they correspond to a UTF-16 BOM, then ripgrep will transcode the contents of
  504. the file from UTF-16 to UTF-8, and then execute the search on the transcoded
  505. version of the file. (This incurs a performance penalty since transcoding
  506. is slower than regex searching.) If the file contains invalid UTF-16, then
  507. the Unicode replacement codepoint is substituted in place of invalid code
  508. units.
  509. * To handle other cases, ripgrep provides a `-E/--encoding` flag, which permits
  510. you to specify an encoding from the
  511. [Encoding Standard](https://encoding.spec.whatwg.org/#concept-encoding-get).
  512. ripgrep will assume *all* files searched are the encoding specified (unless
  513. the file has a BOM) and will perform a transcoding step just like in the
  514. UTF-16 case described above.
  515. By default, ripgrep will not require its input be valid UTF-8. That is, ripgrep
  516. can and will search arbitrary bytes. The key here is that if you're searching
  517. content that isn't UTF-8, then the usefulness of your pattern will degrade. If
  518. you're searching bytes that aren't ASCII compatible, then it's likely the
  519. pattern won't find anything. With all that said, this mode of operation is
  520. important, because it lets you find ASCII or UTF-8 *within* files that are
  521. otherwise arbitrary bytes.
  522. As a special case, the `-E/--encoding` flag supports the value `none`, which
  523. will completely disable all encoding related logic, including BOM sniffing.
  524. When `-E/--encoding` is set to `none`, ripgrep will search the raw bytes of
  525. the underlying file with no transcoding step. For example, here's how you might
  526. search the raw UTF-16 encoding of the string `Шерлок`:
  527. ```
  528. $ rg '(?-u)\(\x045\x04@\x04;\x04>\x04:\x04' -E none -a some-utf16-file
  529. ```
  530. Of course, that's just an example meant to show how one can drop down into
  531. raw bytes. Namely, the simpler command works as you might expect automatically:
  532. ```
  533. $ rg 'Шерлок' some-utf16-file
  534. ```
  535. Finally, it is possible to disable ripgrep's Unicode support from within the
  536. regular expression. For example, let's say you wanted `.` to match any byte
  537. rather than any Unicode codepoint. (You might want this while searching a
  538. binary file, since `.` by default will not match invalid UTF-8.) You could do
  539. this by disabling Unicode via a regular expression flag:
  540. ```
  541. $ rg '(?-u:.)'
  542. ```
  543. This works for any part of the pattern. For example, the following will find
  544. any Unicode word character followed by any ASCII word character followed by
  545. another Unicode word character:
  546. ```
  547. $ rg '\w(?-u:\w)\w'
  548. ```
  549. ### Binary data
  550. In addition to skipping hidden files and files in your `.gitignore` by default,
  551. ripgrep also attempts to skip binary files. ripgrep does this by default
  552. because binary files (like PDFs or images) are typically not things you want to
  553. search when searching for regex matches. Moreover, if content in a binary file
  554. did match, then it's possible for undesirable binary data to be printed to your
  555. terminal and wreak havoc.
  556. Unfortunately, unlike skipping hidden files and respecting your `.gitignore`
  557. rules, a file cannot as easily be classified as binary. In order to figure out
  558. whether a file is binary, the most effective heuristic that balances
  559. correctness with performance is to simply look for `NUL` bytes. At that point,
  560. the determination is simple: a file is considered "binary" if and only if it
  561. contains a `NUL` byte somewhere in its contents.
  562. The issue is that while most binary files will have a `NUL` byte toward the
  563. beginning of its contents, this is not necessarily true. The `NUL` byte might
  564. be the very last byte in a large file, but that file is still considered
  565. binary. While this leads to a fair amount of complexity inside ripgrep's
  566. implementation, it also results in some unintuitive user experiences.
  567. At a high level, ripgrep operates in three different modes with respect to
  568. binary files:
  569. 1. The default mode is to attempt to remove binary files from a search
  570. completely. This is meant to mirror how ripgrep removes hidden files and
  571. files in your `.gitignore` automatically. That is, as soon as a file is
  572. detected as binary, searching stops. If a match was already printed (because
  573. it was detected long before a `NUL` byte), then ripgrep will print a warning
  574. message indicating that the search stopped prematurely. This default mode
  575. **only applies to files searched by ripgrep as a result of recursive
  576. directory traversal**, which is consistent with ripgrep's other automatic
  577. filtering. For example, `rg foo .file` will search `.file` even though it
  578. is hidden. Similarly, `rg foo binary-file` will search `binary-file` in
  579. "binary" mode automatically.
  580. 2. Binary mode is similar to the default mode, except it will not always
  581. stop searching after it sees a `NUL` byte. Namely, in this mode, ripgrep
  582. will continue searching a file that is known to be binary until the first
  583. of two conditions is met: 1) the end of the file has been reached or 2) a
  584. match is or has been seen. This means that in binary mode, if ripgrep
  585. reports no matches, then there are no matches in the file. When a match does
  586. occur, ripgrep prints a message similar to one it prints when in its default
  587. mode indicating that the search has stopped prematurely. This mode can be
  588. forcefully enabled for all files with the `--binary` flag. The purpose of
  589. binary mode is to provide a way to discover matches in all files, but to
  590. avoid having binary data dumped into your terminal.
  591. 3. Text mode completely disables all binary detection and searches all files
  592. as if they were text. This is useful when searching a file that is
  593. predominantly text but contains a `NUL` byte, or if you are specifically
  594. trying to search binary data. This mode can be enabled with the `-a/--text`
  595. flag. Note that when using this mode on very large binary files, it is
  596. possible for ripgrep to use a lot of memory.
  597. Unfortunately, there is one additional complexity in ripgrep that can make it
  598. difficult to reason about binary files. That is, the way binary detection works
  599. depends on the way that ripgrep searches your files. Specifically:
  600. * When ripgrep uses memory maps, then binary detection is only performed on the
  601. first few kilobytes of the file in addition to every matching line.
  602. * When ripgrep doesn't use memory maps, then binary detection is performed on
  603. all bytes searched.
  604. This means that whether a file is detected as binary or not can change based
  605. on the internal search strategy used by ripgrep. If you prefer to keep
  606. ripgrep's binary file detection consistent, then you can disable memory maps
  607. via the `--no-mmap` flag. (The cost will be a small performance regression when
  608. searching very large files on some platforms.)
  609. ### Preprocessor
  610. In ripgrep, a preprocessor is any type of command that can be run to transform
  611. the input of every file before ripgrep searches it. This makes it possible to
  612. search virtually any kind of content that can be automatically converted to
  613. text without having to teach ripgrep how to read said content.
  614. One common example is searching PDFs. PDFs are first and foremost meant to be
  615. displayed to users. But PDFs often have text streams in them that can be useful
  616. to search. In our case, we want to search Bruce Watson's excellent
  617. dissertation,
  618. [Taxonomies and Toolkits of Regular Language Algorithms](https://burntsushi.net/stuff/1995-watson.pdf).
  619. After downloading it, let's try searching it:
  620. ```
  621. $ rg 'The Commentz-Walter algorithm' 1995-watson.pdf
  622. $
  623. ```
  624. Surely, a dissertation on regular language algorithms would mention
  625. Commentz-Walter. Indeed it does, but our search isn't picking it up because
  626. PDFs are a binary format, and the text shown in the PDF may not be encoded as
  627. simple contiguous UTF-8. Namely, even passing the `-a/--text` flag to ripgrep
  628. will not make our search work.
  629. One way to fix this is to convert the PDF to plain text first. This won't work
  630. well for all PDFs, but does great in a lot of cases. (Note that the tool we
  631. use, `pdftotext`, is part of the [poppler](https://poppler.freedesktop.org)
  632. PDF rendering library.)
  633. ```
  634. $ pdftotext 1995-watson.pdf > 1995-watson.txt
  635. $ rg 'The Commentz-Walter algorithm' 1995-watson.txt
  636. 316:The Commentz-Walter algorithms : : : : : : : : : : : : : : :
  637. 7165:4.4 The Commentz-Walter algorithms
  638. 10062:in input string S , we obtain the Boyer-Moore algorithm. The Commentz-Walter algorithm
  639. 17218:The Commentz-Walter algorithm (and its variants) displayed more interesting behaviour,
  640. 17249:Aho-Corasick algorithms are used extensively. The Commentz-Walter algorithms are used
  641. 17297: 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 are
  642. ```
  643. But having to explicitly convert every file can be a pain, especially when you
  644. have a directory full of PDF files. Instead, we can use ripgrep's preprocessor
  645. feature to search the PDF. ripgrep's `--pre` flag works by taking a single
  646. command name and then executing that command for every file that it searches.
  647. ripgrep passes the file path as the first and only argument to the command and
  648. also sends the contents of the file to stdin. So let's write a simple shell
  649. script that wraps `pdftotext` in a way that conforms to this interface:
  650. ```
  651. $ cat preprocess
  652. #!/bin/sh
  653. exec pdftotext - -
  654. ```
  655. With `preprocess` in the same directory as `1995-watson.pdf`, we can now use it
  656. to search the PDF:
  657. ```
  658. $ rg --pre ./preprocess 'The Commentz-Walter algorithm' 1995-watson.pdf
  659. 316:The Commentz-Walter algorithms : : : : : : : : : : : : : : :
  660. 7165:4.4 The Commentz-Walter algorithms
  661. 10062:in input string S , we obtain the Boyer-Moore algorithm. The Commentz-Walter algorithm
  662. 17218:The Commentz-Walter algorithm (and its variants) displayed more interesting behaviour,
  663. 17249:Aho-Corasick algorithms are used extensively. The Commentz-Walter algorithms are used
  664. 17297: 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 are
  665. ```
  666. Note that `preprocess` must be resolvable to a command that ripgrep can read.
  667. The simplest way to do this is to put your preprocessor command in a directory
  668. that is in your `PATH` (or equivalent), or otherwise use an absolute path.
  669. As a bonus, this turns out to be quite a bit faster than other specialized PDF
  670. grepping tools:
  671. ```
  672. $ time rg --pre ./preprocess 'The Commentz-Walter algorithm' 1995-watson.pdf -c
  673. 6
  674. real 0.697
  675. user 0.684
  676. sys 0.007
  677. maxmem 16 MB
  678. faults 0
  679. $ time pdfgrep 'The Commentz-Walter algorithm' 1995-watson.pdf -c
  680. 6
  681. real 1.336
  682. user 1.310
  683. sys 0.023
  684. maxmem 16 MB
  685. faults 0
  686. ```
  687. If you wind up needing to search a lot of PDFs, then ripgrep's parallelism can
  688. make the speed difference even greater.
  689. #### A more robust preprocessor
  690. One of the problems with the aforementioned preprocessor is that it will fail
  691. if you try to search a file that isn't a PDF:
  692. ```
  693. $ echo foo > not-a-pdf
  694. $ rg --pre ./preprocess 'The Commentz-Walter algorithm' not-a-pdf
  695. not-a-pdf: preprocessor command failed: '"./preprocess" "not-a-pdf"':
  696. -------------------------------------------------------------------------------
  697. Syntax Warning: May not be a PDF file (continuing anyway)
  698. Syntax Error: Couldn't find trailer dictionary
  699. Syntax Error: Couldn't find trailer dictionary
  700. Syntax Error: Couldn't read xref table
  701. ```
  702. To fix this, we can make our preprocessor script a bit more robust by only
  703. running `pdftotext` when we think the input is a non-empty PDF:
  704. ```
  705. $ cat preprocessor
  706. #!/bin/sh
  707. case "$1" in
  708. *.pdf)
  709. # The -s flag ensures that the file is non-empty.
  710. if [ -s "$1" ]; then
  711. exec pdftotext - -
  712. else
  713. exec cat
  714. fi
  715. ;;
  716. *)
  717. exec cat
  718. ;;
  719. esac
  720. ```
  721. We can even extend our preprocessor to search other kinds of files. Sometimes
  722. we don't always know the file type from the file name, so we can use the `file`
  723. utility to "sniff" the type of the file based on its contents:
  724. ```
  725. $ cat processor
  726. #!/bin/sh
  727. case "$1" in
  728. *.pdf)
  729. # The -s flag ensures that the file is non-empty.
  730. if [ -s "$1" ]; then
  731. exec pdftotext - -
  732. else
  733. exec cat
  734. fi
  735. ;;
  736. *)
  737. case $(file "$1") in
  738. *Zstandard*)
  739. exec pzstd -cdq
  740. ;;
  741. *)
  742. exec cat
  743. ;;
  744. esac
  745. ;;
  746. esac
  747. ```
  748. #### Reducing preprocessor overhead
  749. There is one more problem with the above approach: it requires running a
  750. preprocessor for every single file that ripgrep searches. If every file needs
  751. a preprocessor, then this is OK. But if most don't, then this can substantially
  752. slow down searches because of the overhead of launching new processors. You
  753. can avoid this by telling ripgrep to only invoke the preprocessor when the file
  754. path matches a glob. For example, consider the performance difference even when
  755. searching a repository as small as ripgrep's:
  756. ```
  757. $ time rg --pre pre-rg 'fn is_empty' -c
  758. crates/globset/src/lib.rs:1
  759. crates/matcher/src/lib.rs:2
  760. crates/ignore/src/overrides.rs:1
  761. crates/ignore/src/gitignore.rs:1
  762. crates/ignore/src/types.rs:1
  763. real 0.138
  764. user 0.485
  765. sys 0.209
  766. maxmem 7 MB
  767. faults 0
  768. $ time rg --pre pre-rg --pre-glob '*.pdf' 'fn is_empty' -c
  769. crates/globset/src/lib.rs:1
  770. crates/ignore/src/types.rs:1
  771. crates/ignore/src/gitignore.rs:1
  772. crates/ignore/src/overrides.rs:1
  773. crates/matcher/src/lib.rs:2
  774. real 0.008
  775. user 0.010
  776. sys 0.002
  777. maxmem 7 MB
  778. faults 0
  779. ```
  780. ### Common options
  781. ripgrep has a lot of flags. Too many to keep in your head at once. This section
  782. is intended to give you a sampling of some of the most important and frequently
  783. used options that will likely impact how you use ripgrep on a regular basis.
  784. * `-h`: Show ripgrep's condensed help output.
  785. * `--help`: Show ripgrep's longer form help output. (Nearly what you'd find in
  786. ripgrep's man page, so pipe it into a pager!)
  787. * `-i/--ignore-case`: When searching for a pattern, ignore case differences.
  788. That is `rg -i fast` matches `fast`, `fASt`, `FAST`, etc.
  789. * `-S/--smart-case`: This is similar to `--ignore-case`, but disables itself
  790. if the pattern contains any uppercase letters. Usually this flag is put into
  791. alias or a config file.
  792. * `-w/--word-regexp`: Require that all matches of the pattern be surrounded
  793. by word boundaries. That is, given `pattern`, the `--word-regexp` flag will
  794. cause ripgrep to behave as if `pattern` were actually `\b(?:pattern)\b`.
  795. * `-c/--count`: Report a count of total matched lines.
  796. * `--files`: Print the files that ripgrep *would* search, but don't actually
  797. search them.
  798. * `-a/--text`: Search binary files as if they were plain text.
  799. * `-U/--multiline`: Permit matches to span multiple lines.
  800. * `-z/--search-zip`: Search compressed files (gzip, bzip2, lzma, xz, lz4,
  801. brotli, zstd). This is disabled by default.
  802. * `-C/--context`: Show the lines surrounding a match.
  803. * `--sort path`: Force ripgrep to sort its output by file name. (This disables
  804. parallelism, so it might be slower.)
  805. * `-L/--follow`: Follow symbolic links while recursively searching.
  806. * `-M/--max-columns`: Limit the length of lines printed by ripgrep.
  807. * `--debug`: Shows ripgrep's debug output. This is useful for understanding
  808. why a particular file might be ignored from search, or what kinds of
  809. configuration ripgrep is loading from the environment.