Update some changed export keybindings
[worg.git] / org-tutorials / advanced-searching.org
blobe1faaf621bfed1ea8dc24f0b909f376b45f6c4d4
1 #+TITLE:      Advanced searching
2 #+AUTHOR:     Matt Lundin
3 #+EMAIL:      mdl at imapmail dot org
4 #+OPTIONS:    H:3 num:nil toc:t \n:nil ::t |:t ^:t -:t f:t *:t tex:t d:(HIDE) tags:not-in-toc
5 #+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate
6 #+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
7 #+TAGS:       Write(w) Update(u) Fix(f) Check(c)
8 #+LANGUAGE:   en
9 #+PRIORITIES: A C B
10 #+CATEGORY:   worg
12 # This file is released by its authors and contributors under the GNU
13 # Free Documentation license v1.3 or later, code examples are released
14 # under the GNU General Public License v3 or later.
16 [[file:index.org][{Back to Worg's index}]]
18 * Introduction
19   :PROPERTIES:
20   :CUSTOM_ID: introduction
21   :END:
23 Org-mode has many powerful built-in search functions. These tools
24 transform hierarchical org files into robust plain text "databases"
25 that can be queried in sophisticated ways. Outline headings in
26 Org-mode not only function as document sections or todo items; each
27 heading can also store an unlimited amount of text and various types
28 of metadata. And, of course, since Org-mode files are plain text, any
29 number of tools (grep, awk, perl, etc.) can be used to filter and
30 manipulate the data they contain.
32 The goal of this tutorial is to offer an introduction to the built-in
33 commands and syntax for querying Org-mode outlines. While these are
34 explained in various places in the Org-mode manual, this tutorial
35 attempts to provide an overview in one place. It is particularly aimed
36 at those who would like to use Org-mode as a note-taking and reference
37 management tool. Nonetheless, it should prove useful to anyone who
38 needs to locate specific information buried in an ever-growing
39 collection of Org-mode data.
41 * Outline nodes as "data containers"
42   :PROPERTIES:
43   :CUSTOM_ID: outline-nodes-as-data-containers
44   :END:
46 Before discussing specific search commands, it is worth taking a few
47 moments to consider the basic structure of an Org-mode entry.
49 Though outline entries can be nested within one another
50 hierarchically, each node is also a discrete container of data.
51 Indeed, a large variety of metadata---a todo keyword, tags,
52 timestamps, logging information, and properties (i.e., arbitrary data
53 pairs)---can be attached to each heading. Similarly each outline entry
54 can store an unlimited amount of text. 
56 Here is an example:
58 #+begin_src org
59   ,* TODO Buy clothes for wedding                    :wedding:important:errands:
60   ,  SCHEDULED: <2010-12-01 Wed>
61   ,  :PROPERTIES:
62   ,  :estimated-cost: 100
63   ,  :END:
64   ,  [2010-11-17 Wed 12:22]
65   
66   ,  I need to look spiffy for the big day!
67   
68   ,   - [ ] Suit
69   ,   - [ ] Tie
70   ,   - [ ] Shoes
71   ,   - [ ] Hat
72   
73   ,  Possible stores to visit:
74   ,  
75   ,  | Store           | Location               | Miles away |
76   ,  |-----------------+------------------------+------------|
77   ,  | The Suit King   | 1000 E. Washington St. |        5.1 |
78   ,  | Mr. Haberdasher | 259 Western Rd.        |        7.2 |
79   
80 #+end_src
82 The sample entry above has the following metadata:
84  - todo keyword :: TODO
85  - scheduled timestamp :: 2010-12-01 Wed
86  - inactive timestamp :: 2010-11-17 Wed 12:22
87  - property :: estimated-cost \Rightarrow 100
88  - tags :: "wedding", "important", and "errands"
90 The entry also contains some text, including a checklist and a table.
92 Normally, an Org-mode file/outline contains several entries such as
93 the one above, nested hierarchically. Moreover, Org users typically
94 make their most important files available for easy searching by adding
95 them to their list of [[https://orgmode.org/manual/Agenda-files.html#Agenda-files][agenda files]], either selecting them one-by-one
96 with =C-c [= or by setting the variable =org-agenda-files=.
98 * The agenda as a search engine
99   :PROPERTIES:
100   :CUSTOM_ID: agenda-as-search-engine
101   :END:
103 For querying a collection of org files, Org-mode includes a powerful
104 built-in search-engine, [[https://orgmode.org/manual/Agenda-views.html#Agenda-views][the agenda]] (=C-c a=). As its name suggests,
105 the most common use of [[https://orgmode.org/manual/Agenda-views.html#Agenda-views][the agenda]] is to pull together, from all the
106 agenda files, a daily or weekly schedule or a list of todos. But the
107 agenda is also a powerful search engine that offers various ways tools
108 for querying both the metadata and the text of org-mode entries. In
109 fact, Org-mode's default agenda view (=C-c a a= or =org-agenda-list=)
110 is simply a search tool that gathers and displays all org-mode entries
111 with certain types of metadata---timestamps that fall within a given
112 range of dates.
114 Typing =C-c a= or =M-x org-agenda= brings up the agenda dispatcher, an
115 overview of Org-mode's various search tools:
117 : Press key for an agenda command:        <   Buffer, subtree/region restriction
118 : --------------------------------        >   Remove restriction
119 : a   Agenda for current week or day      e   Export agenda views
120 : t   List of all TODO entries            T   Entries with special TODO kwd
121 : m   Match a TAGS/PROP/TODO query        M   Like m, but only TODO entries
122 : L   Timeline for current buffer         #   List stuck projects (!=configure)
123 : s   Search for keywords                 C   Configure custom agenda commands
124 : /   Multi-occur                         ?   Find :FLAGGED: entries
126 A quick perusal of [[https://orgmode.org/manual/Built_002din-agenda-views.html#Built_002din-agenda-views][the commands]] here reveals that one can query for a
127 wide variety of data. This tutorial will focus on three searches in
128 particular:
130  - =C-c a T= :: for todo keywords
131  - =C-c a m=  :: for tags and properties
132  - =C-c a s= :: for full text searches
134 Now, let's look at the syntax for each of these search tools.
136 * Searching metadata (todos, tags, and properties)
137   :PROPERTIES:
138   :CUSTOM_ID: searching-metadata
139   :END:
140 ** Todo keyword searches
141    :PROPERTIES:
142    :CUSTOM_ID: todo-keyword-searches
143    :END:
145 The simplest type of metadata query in org-mode is [[https://orgmode.org/manual/Global-TODO-list.html#Global-TODO-list][=org-todo-list=]]
146 (invoked with =C-c a T=). This function prompts the user for a search
147 string and then retrieves a list of outline headings containing the
148 TODOs specified in the search string.[fn:lowercase-t]
150 Since each outline heading can contain only one TODO keyword, the
151 search syntax is quite simple, consisting either of a single keyword
152 or two or more keywords bound together by the boolean operator =|=
153 ("or").
155 For instance, the following query...
157 : TODO
159 ...retrieves all entries marked with a TODO keyword, whereas...
161 : TODO|PROJECT|MAYBE
163 ...displays a list of all headlines containing either TODO or PROJECT
164 or MAYBE.
166 [fn:lowercase-t] Note that the lowercase variant of the command (=C-c
167 a t=) does not provide a search prompt, but simply pulls up all active
168 TODOs.
170 ** Tag searches
171    :PROPERTIES:
172    :CUSTOM_ID: tag-searches
173    :END:
174 #+INDEX: tags
175 #+INDEX: search!tags
177 Though the org-todo-list serves its purpose well, it is limited to
178 only one type of metadata. If you would like to search for other types
179 of metadata, or mix and match a search for todo keywords with, say, a
180 search for tags, org-mode offers a more powerful tool,
181 [[https://orgmode.org/manual/Matching-tags-and-properties.html#Matching-tags-and-properties][=org-tags-view=]], which is called with the following keys:
183    - =C-c a m= :: searches all headlines
184    - =C-c a M= :: searches only headlines with active todos
186 At its simplest, org-tags-view does exactly what it says: it queries
187 for headlines marked with particular combinations of tags. The syntax
188 for such searches follows a simple boolean logic:
190  - =|= :: or
191  - =&= :: and
192  - =+= :: include matches
193  - =-= :: exclude matches
195 Here are a few examples:
197 1. =+computer&+urgent=
199    ...will result in all items tagged both computer *and* urgent,
200    while the search...
202 2. =+computer|+urgent=
204    ...will result in all items tagged *either* computer *or* urgent.
205    Meanwhile, the query...
207 3. =+computer&-urgent=
209    ...will display all items tagged computer *and not* urgent.
211 As you may have noticed, the syntax above can be a little verbose, so
212 org-mode offers convenient ways of shortening it. First, =-= and =+=
213 imply "and" if no boolean operator is stated, so example three above
214 could be rewritten simply as:
216 : +computer-urgent
218 Second, inclusion of matches is implied if no =+= or =-= is present,
219 so example three could be further shortened to:
221 : computer-urgent
223 Example number two, meanwhile, could be shortened to:
225 : computer|urgent
227 *** Grouping tags
228     :PROPERTIES:
229     :CUSTOM_ID: grouping-tags
230     :END:
232 There is no way (as yet) to express search grouping with parentheses.
233 The "and" operators (=&=, =+=, and =-=) always bind terms together
234 more strongly than "or" (=|=). For instance, the following search...
236 : computer|work+email
238 ...results in all headlines tagged either with "computer" or both
239 "work" and "email". An expression such as =(computer|work)&email= is
240 *not* supported at the moment.
242 There, are, however several other ways to achieve the grouping effect
243 of parentheses:
245 1. Use a regular expression
247    To invoke the "grouping" logic of parentheses, you can construct a
248    regular expression:
250    : +{computer\|work}+email
252    Note: you can also use the special property =ALLTAGS= (which
253    queries the same data as a normal tags search) together with a
254    regular expression:
256    : ALLTAGS={computer\|work}+email
257    
258    (In the next section we'll learn more about how property searches
259    and regular expressions are constructed.)
261 2. Use a slightly more verbose query as a substitute for the logic of
262    parentheses. E.g.,
264    : computer&email|work&email
266    This search will match all headlines tagged either with "computer"
267    and "email" or with "work" and "email."
269 3. If you are combining a tags search with a TODO search, you can use
270    the following:
272    : computer|email/!NOW
274 4. Use [[https://orgmode.org/manual/Agenda-commands.html#Agenda-commands][agenda filtering]].
276    Simply search for all headlines tagged with "computer" or "work"
277    and then use the agenda's tag filtering capabilities (=/=) to see
278    only those headlines among the results that have the tag "email."
280 ** Property searches
281    :PROPERTIES:
282    :CUSTOM_ID: property-searches
283    :END:
285 Org-mode allows outline entries to contain any number of [[https://orgmode.org/manual/Properties-and-columns.html#Properties-and-columns][arbitrary
286 data pairs]], which are conveniently hidden within a folding PROPERTIES
287 drawer, e.g.:
289 #+begin_src org
290   ,* TODO Evensong's magisterial work on the Amazon           :science:read:BIB:
291   ,  SCHEDULED: <2010-11-20 Sat>
292   ,  [2010-11-16 Tue 23:11]
293   ,  :PROPERTIES:
294   ,  :BIB_AUTHOR: Walter Evensong
295   ,  :BIB_TITLE: Mysteries of the Amazon
296   ,  :BIB_PAGES: 1234
297   ,  :BIB_PUBLISHER: Humbug University Press
298   ,  :END:
299   ,  
300   ,  Lots of good stuff on Brazil.
301 #+end_src
303 Let's imagine a free software aficionado named Mr. Gnu has added a
304 number of similar bibliographical outline nodes to his org files and
305 that he would like to find all entries that contain "Walter Evensong"
306 in their =BIB_AUTHOR= field. He can construct such a search so by
307 calling =org-tags-view= and entering the desired key/value match:
309 : C-c a m 
310 : Match: BIB_AUTHOR="Walter Evensong"
312 Property searches can be mixed and matched with tag searches. If Mr.
313 Gnu would like to see all books by "Walter Evensong" with the tag
314 "read", he can simply join the two desired matches together with the
315 =+= sign:
317 : BIB_AUTHOR="Walter Evensong"+read
319 Properties with numeric values can be queried with inequalities. If
320 Mr. Gnu would like to retrieve all books by the prolific Walter
321 Evensong that span over 1000 pages, he could enter the following:
323 : BIB_AUTHOR="Walter Evensong"+BIB_PAGES>1000
325 The comparison operators for searches are as follows:
327 : = (equal), > (greater than), <= (greater than or equal to), 
328 : < (less than), <= (less than or equal to), <> (not equal)
330 What if Mr. Gnus would to like of find all books by Walter Evensong
331 *or* any books over 1000 pages?
333 : BIB_AUTHOR="Walter Evensong"|BIB_PAGES>1000
335 For his own clarity, Mr. Gnu can always insert "+" signs, though they
336 are not required:
338 : +BIB_AUTHOR="Walter Evensong"|+BIB_PAGES>1000
340 It is important to note that the equal sign in the searches above
341 implies an exact match. If Mr. Gnu is searching for a string, such as
342 "Mysteries of the Amazon", the entire search query must match. Thus,
343 the search...
345 : BIB_TITLE="Amazon"
347 ...will not match the entry above. 
349 How then can you search for partial matches? The answer is regular
350 expressions. Instead of surrounding your query with quotation marks
351 (which will necessitate a precise and complete match), you can instead
352 enfold it in brackets, which instructs Org-mode to treat the query as
353 a regular expression. Thus, the search...
355 : BIB_TITLE={Amazon}
357 ...will locate all entries that match contain the sequence "Amazon"
358 and pull them up in the agenda:
360 : Headlines with TAGS match: BIB_TITLE={Amazon}
361 : Press `C-u r' to search again with new search string
362 :  org:        TODO Evensong's magisterial work on the Amazon  :science:read:BIB:
364 Mr. Gnu jots down the following rule in his growing org file collection:
366 #+begin_src org
367   ,* Tags/property search matching
368   , - For exact matches, use quotation marks.
369   , - For partial matches, use curly brackets.
370 #+end_src
372 [[http://www.gnu.org/s/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions][Regular expressions]] allow for more flexible searches. Let's say that
373 for some strange reason Mr. Gnu would like to find all books
374 containing either "Amazon" or "Amazing" in their titles. The following
375 regular expression search should do the trick:
377 : BIB_TITLE={Amaz\(on\|ing\)}
379 Let's break this expression down:
381  - =Amaz= :: This is the string shared by both words.
382  - =\(...\)= :: These parentheses create a grouping to set off the
383               alternative matches that follow "Amaz".
384  - =on\|ing= :: =\|= is the "or" expression. Since it is placed within
385               the parentheses, it means that a match must begin with
386               "Amaz" but can end *either* in "on" *or* "ing".
388 You may be wondering why the search query contains so many
389 backslashes. It is because Emacs' regular expression engine gives the
390 characters =(=, =)=, and =|= a special meaning only when they are
391 "escaped" (i.e., preceded by a backslash). Thus, Mr. Gnu had simply
392 typed =BIB_TITLE={Amaz(on|ing)}=, he would have instructed Org-mode to
393 match entries with the exact sequence =Amaz(on|ing)= (an unlikely
394 match, unless he has a large collection of literary theory from the
395 1990s).
396               
397 Here's a simpler example. If Mr. Gnu would like to find all entries
398 with either "Walter" or "Evensong" in the author field, he could type:
400 : BIB_TITLE={Walter\|Evensong}
402 If he would like to pull up all entries that have defined value for
403 the =BIB_TITLE= property, he can simply use a single dot to match any
404 character:
406 : BIB_TITLE={.}
408 ** Special Properties
409    :PROPERTIES:
410    :CUSTOM_ID: special-properties
411    :END:
413 In addition to any explicitly declared key/value property pairs, each
414 Org-mode entry also has a number of [[https://orgmode.org/manual/Special-properties.html#Special-properties][special (i.e., implicit)
415 properties]] that can be queried with =org-tags-view= (=C-c a m=). These
416 include, among other things, the entry's TODO state, tags (local and
417 inherited), category, priority, and timestamps (DEADLINE, SCHEDULED,
418 active, and inactive). See the [[#outline-nodes-as-data-containers][sample entry]] above for an illustration
419 of where these properties are typically found in an outline node.
421 To see all of the properties (both explicit and implicit) defined for
422 an Org-mode entry, place the following text in an org-mode entry and
423 evaluate it by typing C-x C-e after the closing parenthesis:
425 : (org-entry-properties nil)
427 Here's an example of how such "special properties" can be put to good
428 use in a search:
430 : C-c a m
431 : Match: Effort>1+PRIORITY="A"+SCHEDULED<"<tomorrow>"+ALLTAGS={computer\|email}
433 This query finds all items with:
435 1. An estimated effort greater than one hour
436 2. A priority of "A"
437 3. A scheduled date "less than" tomorrow (i.e., today or earlier).
438 4. Either the tag "computer" or the tag "email"
439    - Note: the ALLTAGS property includes inherited tags, while the
440      TAGS property includes only local tags.
441    - This search is also a good example of how to achieve a [[#grouping-tags][grouping
442      logic without parentheses]] while querying tags.
444 Please [[https://orgmode.org/manual/Matching-tags-and-properties.html][consult the manual]] for a fuller explanation of the syntax of
445 such searches.
447 *** Querying timestamps
448     :PROPERTIES:
449     :CUSTOM_ID: querying-timestamps
450     :END:
452 A few words should be said here about querying timestamps contained in
453 the following properties: =DEADLINE=, =SCHEDULED=, =TIMESTAMP= (the
454 first active timestamp in an entry), and =TIMESTAMP_IA= (the first
455 inactive timestamp in an entry).
457 The basic syntax for querying timestamps is a time string enclosed in
458 double quotes and angular brackets. E.g., the search...
460 : C-c a m
461 : Match: +SCHEDULED="<2010-08-20 Sat>"
463 ...will find all items scheduled for Saturday, August 20, 2010
464 *without* a time of day specification. This last caveat is important
465 to note: if you have a timestamp with time of day information, such
466 as...
468 #+begin_src org
469   ,* Some task
470   ,  SCHEDULED: <2010-08-20-Sat 10:30>
471 #+end_src
473 ...the search above will not retrieve it. (This is not normally a
474 problem, since the daily/weekly agenda view provides a far superior
475 mechanism for viewing all timestamps that fall on a particular day.)
477 The true value of timestamp property queries lies in the use of
478 inequalities to capture a range of dates. To assist with this task,
479 Org-mode provides a number of convenient shortcuts:
481  - =<today>= and =<tomorrow>= :: timestamps for today and tomorrow
482       (without a time of day specification)
483  - =<now>= :: right now, including time of day
484    - e.g., =2010-11-20 Sat 12:42=
485  - =<-5d>=, =<-10w>=, =<+3m>=, =<+1y>= :: relative date indicators
486     - the shortcuts above indicate five days ago, ten weeks ago, three
487       months from now, and one year from now
489 To see all items SCHEDULED far in the future, say, more than a year
490 from now, you could type:
492 : C-c a m
493 : Match: SCHEDULED>"<+1y>"
495 Here's another scenario. Imagine you use org-capture to take all your
496 notes and that you automatically stamp each notes with an inactive
497 timestamp. To find all notes you took in the past two weeks with the
498 tag "chimpanzees", you could perform the following search:
500 : C-c a m
501 : Match: chimpanzees+TIMESTAMP_IA>="<-2w>"
503 *** Limit tags and properties searches by TODO state
504     :PROPERTIES:
505     :CUSTOM_ID: limiting-searches-to-todos
506     :END:
508 You can limit any of these tags/property searches to active todo
509 states simply by using =C-c a M= instead of =C-c a m=.
511 You can also, of course, limit the searches to a particular todo
512 keyword (say, NEXT) by adding...
514 : +TODO="NEXT"
516 ...to any of the searches above. But Org-mode also provides a
517 convenient (and more efficient) syntax for limiting searches to
518 particular TODO keywords. Simply add a =/= followed by a TODO search
519 in the form [[#todo-keyword-searches][we've already discussed]]. For instance, to limit the
520 chimpanzee search above to items marked DONE, you could type:
522 : C-c a m
523 : Match: chimpanzees+TIMESTAMP_IA>="<-2w>"/DONE
525 As with normal todo searches, you can use or (=|=) to expand the
526 allowed matches. For instance, the query...
528 : chimpanzees+TIMESTAMP_IA>="<-2w>"/TODO|NEXT
530 ...will match against items marked either TODO or NEXT.
532 If you are matching only against active todos (i.e., things not marked
533 done), you can make your search more efficient by adding an exclamation
534 point. E.g., the following search...
536 : computer/!TODO|NEXT
538 ...will result in all items tagged "computer" and either a TODO or
539 NEXT keyword. The exclamation mark will speed up the search, because
540 org-mode will only query items that have an active todo keyword (as
541 defined either in the variable =org-todo-keywords= or in =#+TODO=
542 declarations at the top of an org file). For instance, if you had
543 placed the following line at the top of your org files...
545 : #+TODO: TODO NEXT STARTED WAITING | DONE CANCELED
547 ...an exclamation point limit the possible matches items marked TODO,
548 NEXT, STARTED, or WAITING.
550 You can use a a negative (=-=) to exclude TODO states. The search...
552 : computer/!-WAITING
554 ...will result only in items marked TODO, NEXT, or STARTED.
556 Be careful to avoid using "and" logic when you query TODOs, since each
557 item, by definition can have only one TODO state. Take a look at the
558 following two searches:
560 : computer/!WAITING+TODO
562 : chimpanzees+TODO="TODO"+SCHEDULED<="<+1w>"+TODO="WAITING"
564 These searches will *never* return any positive results, since an org
565 entry cannot have both a TODO *and* a WAITING keyword.
567 * Searching the full text of entries
568   :PROPERTIES:
569   :CUSTOM_ID: searching-entry-text
570   :END:
571 ** Keyword searches
572    :PROPERTIES:
573    :CUSTOM_ID: keyword-searches
574    :END:
576 Thus far, we have explored different ways to query the various types
577 of metadata attached to an org entry. But what if you would like to
578 search the entire text of your org entries?
580 The answer: call [[https://orgmode.org/manual/Search-view.html#Search-view][=org-search-view=]] with =C-c a s=. In the agenda
581 dispatcher, this appears as...
583 : s  Search for keywords
585 Don't be fooled by the word "keywords," which some programs use as a
586 synonym for tags. Here, a keyword search scours the full text of org
587 entries.
589 Let's start with an example:
591 Desperately in need of typing practice (as if Emacs does not provide
592 enough keyboarding practice), our friend Mr. Gnu would like to locate
593 the following entry, which is buried somewhere in his agenda files:
595 #+begin_src org
596   ,* A sentence to test my keyboarding skills
597   
598   ,The quick brown fox jumped over the lazy dog.
599 #+end_src
601 Mr. Gnu vaguely remembers that the entry contains the word "fox", so
602 he pecks at the keyboard to enter...
604 : C-c a s 
606 He is confronted with the prompt...
608 : [+-]Word/{Regexp} ...: 
610 ...so he enters...
612 : fox
614 ...and receives an agenda buffer with the correct results:
616 : Search words: fox
617 : Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit
618 :  typing:        A sentence to test my keyboarding skills
620 Here, we should note that Org-mode's keyword searches are
621 *case-insensitive*, so "fox" will match any of the following: "fox",
622 "Fox", "FOX", etc.
624 Let's say, however, that Mr. Gnu's day job involves studying the
625 behavior of foxes, so he knows ahead of time that a simple search will
626 bring up hundreds of results. In addition, he recalls that the desired
627 entry also contains the word "dog". Thus, he enters the following:
629 : C-c a s
630 : [+-]Word/{Regexp} ...: fox dog
632 Somewhat puzzlingly, Mr. Gnu's search yields no results. What went
633 wrong?
635 Mr. Gnu consults [[https://orgmode.org/manual/Search-view.html#Search-view][the manual]] and finds that the default behavior of
636 =org-search-view= is to treat the entered query as a single string, so
637 when he typed =fox dog=, Org-mode looked quite literally for
638 =fox[whitespace]dog=.
640 Mr. Gnu further finds that to treat "dog" and "fox" as boolean
641 keywords that can be located anywhere in the entry, he needs to
642 precede each term with a =+=. (Technically, he only needs to precede
643 the first search term with =+= to initiate a boolean search, but he
644 decides to put =+= in front of both for the sake of clarity.) So he
645 types...
647 : C-c a s
648 : [+-]Word/{Regexp} ...: +fox +dog
650 ...and is overjoyed to retrieve the expected results.
652 Mr. Gnu makes a mental note: unless the first character of the search
653 query is a =+=, Org-mode will treat the entire query as a single
654 string. Thus, the query...
656 : fox +dog
658 ...will prompt Org-mode to search for the single string "fox +dog".
659 (To change this behavior, please read the
660 [[#boolean-searches-by-default][section for "Google addicts" below]].)
662 Later, while at work, Mr. Gnu  wants to find all entries on foxes that
663 do not contain the word dog, so he types...
665 : C-c a s
666 : [+-]Word/{Regexp} ...: +fox -dog
668 If Mr. Gnu wants to incorporate a substring/phrase into a boolean
669 search (i.e., a query with a =+= at the beginning), he can use
670 quotation marks:
672 : +fox +"lazy dog"
674 At home again, while practicing typing, Mr. Gnu wants to find all
675 entries that contain either the word "keyboarding" or the word
676 "typing". Remember his lessons on tag searches, he tries the following
677 search query:
679 : +keyboarding|+typing
681 Alas, the search returns no results, because Mr. Gnu just instructed
682 Org-mode to look for the entire string "keyboarding|+typing." Reading
683 the manual, Mr. Gnu discovers that, unlike todo and tag searches,
684 keyword searches require separate terms to be separated by whitespace
685 (e.g., =+fox +dog=). In addition, Mr. Gnus realizes that keyword
686 searches have only two simple boolean expressions: =+= ("and") and =-=
687 ("and not"). There is no "or" symbol, such as =|=. What then should
688 Mr. Gnu do to find entries containing keyboarding *or* typing?
690 ** Full text search using regular expressions 
691    :PROPERTIES:
692    :CUSTOM_ID: regexps-in-org-search-view
693    :END:
695 The solution to Mr. Gnu's puzzle is found in regular expressions.
696 Indeed, Mr. Gnu deduced as much by glancing at the org-search-view
697 prompt:
699 : [+-]Word/{Regexp} ...:
701 As the prompt suggests, Mr. Gnu can search org-entries using Emacs'
702 powerful regular expression engine. To do so, he simply needs to
703 enclose the regular expression in brackets. So he types...
705 : C-c a s
706 : [+-]Word/{Regexp} ...: +{keyboarding\|typing}
708 ...to find all entries that contain either "keyboarding" or "typing".
709 (Mr. Gnu could also have used parentheses to create a more compact
710 search query, such as =+{\(keyboard\|typ\)ing}=. Also, it is good to
711 recall here that =(=, =|=, and =)= only become special characters only
712 when escaped with a =\=.)
714 Regular expressions, Mr. Gnu finds, can be combined with words. The
715 query...
717 : +{keyboarding\|typing} +fox
720 ...finds the "quick brown fox" entry above, while...
723 : +{keyboarding\|typing} -fox
725 ...excludes it, finding only those entries that contain either the
726 word "keyboarding" or "typing" and *not* the word dog.
728 Again, Org-mode's default behavior is to treat the entire query as a
729 single string unless it sees a =+= or a ={= at the beginning of the
730 line. So if Mr. Gnus types...
732 : dog +{keyboarding\|typing} 
734 ...Org-mode will search for the entire substring "dog
735 +{keyboarding\|typing}". (If you don't like this behavior, please read
736 [[#boolean-searches-by-default][the section for "Google addicts" below]].)
738 *** Regular expression syntax
739     :PROPERTIES:
740     :CUSTOM_ID: regular-expression-syntax
741     :END:
743 The possibilities afforded by regular expressions are myriad. The
744 examples discussed here are relatively basic. For a thorough
745 introduction to regular expression syntax, please consult the [[http://www.gnu.org/s/emacs/manual/html_node/elisp/Syntax-of-Regexps.html#Syntax-of-Regexps][emacs
746 lisp manual]].
748 Let's look at a couple of examples:
750 Imagine you've entered a lot of contact entries with phone numbers in
751 the conventional U.S. format: 123-456-6789. To find all Org-mode
752 entries with such numbers, you could type:
754 : C-c a s
755 : [+-]Word/{Regexp} ...: +{[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}}
757 The square brackets here are special characters; they match any of
758 characters they enclose. For instance, =[abc]= matches either a or b
759 or c. In this particular case, the =[0-9]= matches any digit between 0
760 and 9. In addition, the escaped curly brackets (=\{...\}=) that
761 immediate follow the square brackets indicate how many times in a row
762 the character should occur. In this case, Org-mode will search for
763 the following sequence:
765   - exactly three digits
766   - a hyphen
767   - exactly three digits
768   - a hyphen
769   - exactly four digits
771 Instead of specifying the precise number of times a match such as
772 =[0-9]= must repeat, you can also use the following special
773 characters:
775  - =*= :: match any number of times (including none)
776  - =+= :: match at least once and possibly more
777  - =?= :: match either once or not at all
779 Now, imagine our friend Mr. Gnu is a new fan of Org-mode and has
780 jotted down a lot of notes on his favorite PIM. However, he have
781 entered the name Org-mode inconsistently, sometimes as "orgmode",
782 other times as "Org mode", and still other times as "Org-mode". He'd
783 like to find all his references to Org-mode, taking into account the
784 various spellings. Here's a simple query that will accomplish this:
786 : +{org[-\s]?mode}
788 Mr. Gnu just instructed Org-mode to search for any entry that contains
789 the character sequence "org", followed by a hyphen, a space, or no
790 character, followed by "mode". Since the search is case-insensitive,
791 it will match "org-mode", "org mode", or "orgmode".
793 ** Limiting full text searches
794    :PROPERTIES:
795    :CUSTOM_ID: limiting-full-text-searches
796    :END:
798 There are several convenient ways to refine and limit full text
799 searches.
801 First, if you find that a search produces too many results, you can
802 easily add a new word or regexp by typing any of the following in the
803 agenda buffer:
805  - =[= :: add a word (i.e., =+=)
806  - =]= :: exclude a word (i.e., =-=)
807  - ={= :: add a regexp (i.e., =+{}=)
808  - =}= :: exclude a regexp (i.e., =-{}=)
810 Let's say Mr. Gnu searches for the words Carsten *and* Dominik:
812 : C-c a s
813 : [+-]Word/{Regexp} ...: +Carsten +Dominik
815 Since Mr. Gnu is an avid reader of the Org-mode mailing list and a
816 heavy user of org-capture, he discovers that he has hundreds of
817 entries that include Carsten's name. He wants to limit the search only
818 to entries with an inactive timestamp from November of 2010. So he
819 types =[= in the agenda buffer to add a new search term and receives the
820 following prompt...
822 : [+-]Word/{Regexp} ...: +Carsten +Dominik +
824 ...with the cursor conveniently located after the plus sign. He
825 completes the query to find inactive timestamps from November...
828 : [+-]Word/{Regexp} ...: +Carsten +Dominik +[2010-11-
830 ...and voilà, he retrieves a smaller subset of results.
832 If Mr. Gnu wants to find both active and inactive timestamps, he could
833 instead type ={= to add a regular expression:
835 : [+-]Word/{Regexp} ...: +Carsten +Dominik +{[\[<]2010-11-}
837 Similarly, if Mr. Gnu wants to guarantee the precision of his match,
838 he could use a detailed regular expression...
840 : +{\[2010-11-[0-9]\{2\}\s-[A-Za-z]\{3\}\(\s-[0-9]\{2\}:[0-9]\{2\}\)?\]}
842 But Mr. Gnu quickly decides that searching for the string "[2010-11-"
843 good enough for his purposes.
845 Org-mode also provides convenient syntax for limiting full text
846 searches.
848 1. If you place an asterisk at the beginning of your search, Org-mode
849    will search only headlines (and not entry text). E.g., to find all
850    entries with "emacs" in the headline, you could type:
852    : C-c a s
853    : [+-]Word/{Regexp} ...: *+emacs
855 2. If you place an exclamation mark at the beginning of the query,
856    Org-mode will only pull up entries that are active todos:
858    : !+emacs
860    (You can also limit your search to active todos by using a prefix
861    argument: =C-u C-c a s=.)
863 3. Finally, if you place a colon at the beginning of a query, the
864    boolean words you provide will only match entire words. Thus the
865    following search...
867    : :+emacs
869    ...will match "emacs" but not "emacswiki".
871 You can mix and match these three limiting symbols, but they will only
872 work if they appear in the correct order: i.e., =*= -> =!= -> =:=. If
873 you type =:!+emacs=, your search will not retrieve any results.
875 ** Combining metadata and full text queries
876    :PROPERTIES:
877    :CUSTOM_ID: combining-metadata-and-full-text-queries
878    :END:
880 As an expert on tag and property searches, you might ask: is it
881 possible to combine metadata and full text searches? For instance, how
882 could Mr. Gnu find all entries with "Walter Evensong" in the
883 =BIB_AUTHOR= field, the todo keyword "DONE", and the word "Brazil" in
884 the full text of the entry?
886 - It is not possible to simply combine the syntax of metadata and
887   full text searches. Org-mode parses each query in fundamentally
888   different ways.
890 - You can, however, easily accomplish "mixed" queries by using regular
891   expressions and =org-search-view=. In some instances,
892   =org-search-view= offers an easier and more efficient way of
893   querying metadata than the tags and property search.
895 The simplest way to think about Org-mode metadata is as different
896 types of markup patterns. Tags are enclosed in colons, todo keywords
897 directly follow the asterisks that mark outline headings, timestamps
898 are contained in brackets and have the pattern =YYYY-MM-DD DOW HH:MM=,
899 and so on. Thus, to query for particular types of metadata, one simply
900 has to construct regular expressions that match these patterns.
902 Back to Mr. Gnu, our mediocre typist and reader of very long books.
903 Today, he would like to find all entries in which:
905  - the =BIB_AUTHOR= is "Walter Evensong"
906  - the todo keyword is "DONE"
907  - the word "Brazil" appears in the full text. 
909 First, he invokes =org-search-view=:
911 : C-c a s
913 At the prompt, he adds a plus sign and the word "brazil":
915 : [+-]Word/{Regexp} ...: +brazil
917 He remembers that he must add the plus sign to instruct Org-mode to
918 treat this search as a boolean search. Otherwise it will simply look
919 for the entire string entered at the prompt.
921 Next he needs to search for the todo keyword "DONE". Since todo
922 keywords immediately follow the markup for outline headings, he can
923 simply add a regexp that matches an outline heading immediately
924 followed by the word DONE:
926 : [+-]Word/{Regexp} ...: +brazil +{^\*+\s-+DONE\s-}
928 This regexp begins with =^=, which forces a match at the beginning of
929 the line. It is followed by an asterisk, which needs to be escaped,
930 since an asterisk a special character in regular expressions. the =+=
931 after the asterisk instructs Org-mode to look for one or more
932 asterisks, while the =\s-+= indicates that at least one space follows
933 the asterisk(s). So Mr. Gnu is searching for at least one asterisk at
934 the beginning of the line followed by a space---the very definition of
935 an outline heading in Org-mode. And the keyword DONE followed by
936 whitespace completes the match. If Mr. Gnu would like to match more
937 than one todo keyword, say DONE or WAITING, he could use grouping:
938 =+{^\*+\s-+\(DONE\|WAITING\)\s-}=
940 Finally, Mr. Gnu finishes his query by searching for the property
941 =BIB_AUTHOR=. He recalls that a property line looks like this:
943 : :BIB_AUTHOR: Walter Evensong
945 With this in mind, he can easily construct a regexp to search for the
946 string =:BIB_AUTHOR:= followed by an arbitrary amount of whitespace
947 followed in turn by the string "Walter Evensong".
949 : [+-]Word/{Regexp} ...: +brazil +{^\*+\s-+DONE\s-} +{:BIB_AUTHOR:\s-+Walter Evensong}
951 Mr. Gnu is surprised at the speed with which Org-mode returns his
952 results. Indeed, he finds that regexp searches (especially those
953 querying properties) usually return their results more quickly than
954 property and tag searches. And he deduces the reason: whereas property
955 searches have to query each headline to determine whether a given
956 property contains a value, keyword searches simply scan each file for
957 matches and then return the appropriate headlines.
959 In many instances, of course, the DONE regexp above may be overkill.
960 Searching for the string "* DONE" will often do the trick. E.g.,
962 : [+-]Word/{Regexp} ...: +brazil +"* DONE"
964 Indeed, Mr. Gnu could probably also dispense with the =:BIB_AUTHOR:=
965 regexp above, simply typing...
967 : [+-]Word/{Regexp} ...: +brazil +"* DONE" +":BIB_AUTHOR: Walter Evensong"
969 Here's another example. Let's say Mr. Gnu would like to find all
970 active todos directly tagged "urgent" (i.e., not inherited) with the
971 word "wedding" somewhere in the entry text. The following keyword
972 search does the trick:
974 : C-c a s
975 : [+-]Word/{Regexp} ...: !+wedding :urgent:
977 If Mr. Gnu wants to see either the tag "urgent" or the tag
978 "important", he could use a regular expression:
980 : !+wedding +{:\(urgent\|important\):}
982 The main limitation of such searches is that keyword searches know
983 nothing of outline tree inheritance. Thus, if Mr. Gnu is interested in
984 all entries that inherit the tag "urgent", he should always use
985 =org-tags-view=.
987 ** Searching additional files
988    :PROPERTIES:
989    :CUSTOM_ID: searching-additional-files
990    :END:
992 Often, the set of files one would like to search by keyword is larger
993 than one's set of active agenda files. For instance, one might archive
994 old projects in separate files so that they no longer contribute to
995 the agenda. Yet one would still like to search the reference material
996 in these projects by keyword/regexp.
998 The solution lies in the variable
999 =org-agenda-text-search-extra-files=. Adding a list of files to this
1000 variable instructs =org-search-view= to query those files in addition
1001 to the agenda files. Note that setting
1002 =org-agenda-text-search-extra-files= has no effect on other types of
1003 agenda commands, such as todo and tags/property searches.
1005 ** Keyword searches for Google addicts
1006    :PROPERTIES:
1007    :CUSTOM_ID: boolean-searches-by-default
1008    :END:
1010 As noted before, =org-search-view= will treat a search query as a
1011 boolean expression only if it begins with either a =+= or a ={= (i.e.,
1012 a regular expression). Without these characters, Org-mode will treat
1013 the query as a single substring.
1015 This default syntax of =org-search-view= is thus different than the
1016 behavior of search engines such as Google, which treat searches as
1017 lazy boolean queries by default. If you type "emacs org-mode" into
1018 Google, it will not search for the literal string "emacs org-mode",
1019 but rather assume the space implies a boolean expression: "emacs and
1020 org-mode".
1022 If you find yourself often forgetting to add an initial =+= to your
1023 =org-search-view= queries, you can make "lazy booleans" the default
1024 behavior by adding the following to your .emacs:
1026 #+begin_src elisp
1027 (setq org-agenda-search-view-always-boolean t)
1028 #+end_src
1030 Then you can happily type your lazy searches:
1032 : C-c a s
1033 : [+-]Word/{Regexp} ...: org mode Carsten :email:
1035 If you would like to include a substring or phrase in your search, you
1036 can do so by enclosing it in quotation marks. And if you want to
1037 exclude items or use regular expressions, you will, of course, still
1038 have to use a minus sign and curly brackets, respectively.
1040 * Searching org files line-by-line
1041   :PROPERTIES:
1042   :CUSTOM_ID: line-by-line-search
1043   :END:
1045 All the searches we have discussed thus far return their results as a
1046 list of org headlines in the agenda buffer. Sometimes, however, you
1047 might prefer to see each line in which a word or regular expression
1048 occurs. There are different ways to do this:
1050 ** Multi-occur
1051    :PROPERTIES:
1052    :CUSTOM_ID: multi-occur
1053    :END:
1055 Org-mode uses Emacs' multi-occur command to search for any lines in
1056 the agenda files containing a regular expression. Simply type =C-c a
1057 /= followed by a word or regular expression and you will be presented
1058 a buffer with all lines that match the query, with each line
1059 conveniently linked to its original location.
1061 ** External commands and scripts
1062    :PROPERTIES:
1063    :CUSTOM_ID: grep-etc
1064    :END:
1066 Emacs provides convenient interfaces to common Unix search commands,
1067 such as grep. Simply type =M-x grep= and complete the query (the
1068 working directory is usually that of the current buffer in Emacs).
1069 Using grep is especially convenient when you want quickly to search
1070 org files that are not in =org-agenda-files= or
1071 =org-agenda-text-search-extra-files=. And, of course, grep can be used
1072 outside of Emacs.
1074 Since org-mode files are plain text, you can use your favorite
1075 scripting language (perl, awk, python, etc.) to develop new and ever
1076 more creative ways to search and analyze them.
1078 * Sparse trees
1079   :PROPERTIES:
1080   :CUSTOM_ID: sparse-tree-view
1081   :END:
1083 The commands we have examined so far typically search multiple files
1084 and display the resulting heading in a separate agenda buffer. But
1085 sometimes, you might want to search for various types of data within a
1086 single file, so as to see all the matching headlines and entries in
1087 context.
1089 The way to accomplish this is via a [[https://orgmode.org/manual/Sparse-trees.html#Sparse-trees][sparse tree view]] (=C-c /=), which
1090 collapses the outline in the current file, showing only the portions
1091 that match a query.
1093 Calling =org-sparse-tree= with =C-c /= brings up a prompt with several
1094 search options:
1096 : Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
1097 :              [d]eadlines [b]efore-date [a]fter-date
1099 Some of these search, such as "todo" (=t=) and "deadlines" (=d=) are
1100 quite simple, showing all headlines in a buffer that contain an active
1101 todo keyword or a deadline, respectively. Others, such as "property"
1102 (=p=), prompt for a single key/value pair.
1104 One search that may be of particular interest is "match" (=m=). This
1105 query uses exactly the same syntax as =org-tags-view=, allowing us to
1106 use complex metadata searches to create sparse trees
1108 For instance, to highlight all active todos *without* a timestamp in
1109 the current buffer, you could type:
1111 : C-c / m 
1112 : Match: -SCHEDULED={.}/!
1114 This instructs Org-mode to look for any active todo (=/!=) without a
1115 SCHEDULED timestamp.
1117 * Custom agenda commands
1118   :PROPERTIES:
1119   :CUSTOM_ID: custom-agenda-commands
1120   :END:
1122 If there are searches you perform again and again, you can easily save
1123 them by adding them to you [[https://orgmode.org/manual/Custom-agenda-views.html#Custom-agenda-views][custom agenda commands]].
1125 As we know, Mr. Gnu is an avid collector of very large books (which,
1126 of course, he manages in very long org files). Moreover, he often
1127 likes to peruse your inventory of books over 1,000 pages, querying his
1128 custom =BIB_PAGES= field. To save time and energy, Mr. Gnu could add a
1129 custom command such as the following to his =.emacs=:
1131 #+begin_src emacs-lisp
1132   (add-to-list 'org-agenda-custom-commands
1133                '("b" "Big books" tags "+BIB_PAGES>1000"))
1134 #+end_src
1136 Note that "tags" here indicates =org-tags-view=. Thus, the query uses
1137 the tags/property search syntax.
1139 Mr. Gnu realizes he can save an even faster version of the search
1140 above:
1142 #+begin_src emacs-lisp
1143   (add-to-list 'org-agenda-custom-commands
1144                '("B" "Big books (fast)" search "{:BIB_PAGES:\\s-+[0-9]\\{4\\}}"))
1145 #+end_src
1147 The symbol "search", as you might have guessed, instructs Org-mode to
1148 use =org-search-view=. And the saved search finds all items with
1149 =BIB_PAGES= property that contain four digits (i.e., > 1000 pages).
1151 You might notice that the search query here, compared with the one
1152 above, contains extra backslashes. That is because the backslash is a
1153 special character in emacs-lisp and thus needs to be escaped when
1154 placed in an =.emacs= file.
1156 If Mr. Gnu frequently need to perform the "urgent wedding tasks"
1157 search above, he could add a command such as the following:
1159 #+begin_src emacs-lisp
1160   (add-to-list 'org-agenda-custom-commands
1161                '("w" "Getting married next week!" 
1162                  search "!+wedding +{:\\(urgent\\|important\\):}"))
1163 #+end_src
1165 Finally, one can use custom commands to run searches with different
1166 local settings. For instance, one can set up a custom agenda command
1167 to run a tags/property search on files other than the agenda files:
1169 #+begin_src emacs-lisp
1170   (add-to-list 'org-agenda-custom-commands
1171                '("r" "Reference material" tags ""
1172                  ((org-agenda-files (file-expand-wildcards "~/ref/*.org")))))
1173 #+end_src
1175 For a full introduction to custom agenda commands, please see [[file:org-custom-agenda-commands.org][this
1176 tutorial]].