Add link to Org Babel section from Worg main page
[Worg.git] / org-tutorials / advanced-searching.org
blob7fa8b2cdbb0a43fc5d94b62185f68b4942ea2dae
1 #+OPTIONS:    H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate
3 #+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS:       Write(w) Update(u) Fix(f) Check(c)
5 #+TITLE:      Advanced searching
6 #+AUTHOR:     Matt Lundin
7 #+EMAIL:      mdl at imapmail dot org
8 #+LANGUAGE:   en
9 #+PRIORITIES: A C B
10 #+CATEGORY:   worg
12 [[file:index.org][{Back to Worg's index}]]
14 * Introduction
15   :PROPERTIES:
16   :CUSTOM_ID: introduction
17   :END:
19 Org-mode has many powerful built-in search functions. These tools
20 transform hierarchical org files into robust plain text "databases"
21 that can be queried in sophisticated ways. Outline headings in
22 Org-mode not only function as document sections or todo items; each
23 heading can also store an unlimited amount of text and various types
24 of metadata. And, of course, since Org-mode files are plain text, any
25 number of tools (grep, awk, perl, etc.) can be used to filter and
26 manipulate the data they contain.
28 The goal of this tutorial is to offer an introduction to the built-in
29 commands and syntax for querying Org-mode outlines. While these are
30 explained in various places in the Org-mode manual, this tutorial
31 attempts to provide an overview in one place. It is particularly aimed
32 at those who would like to use Org-mode as a note-taking and reference
33 management tool. Nonetheless, it should prove useful to anyone who
34 needs to locate specific information buried in an ever-growing
35 collection of Org-mode data.
37 * Outline nodes as "data containers"
38   :PROPERTIES:
39   :CUSTOM_ID: outline-nodes-as-data-containers
40   :END:
42 Before discussing specific search commands, it is worth taking a few
43 moments to consider the basic structure of an Org-mode entry.
45 Though outline entries can be nested within one another
46 hierarchically, each node is also a discrete container of data.
47 Indeed, a large variety of metadata---a todo keyword, tags,
48 timestamps, logging information, and properties (i.e., arbitrary data
49 pairs)---can be attached to each heading. Similarly each outline entry
50 can store an unlimited amount of text. 
52 Here is an example:
54 #+begin_src org
55   ,* TODO Buy clothes for wedding                    :wedding:important:errands:
56   ,  SCHEDULED: <2010-12-01 Wed>
57   ,  :PROPERTIES:
58   ,  :estimated-cost: 100
59   ,  :END:
60   ,  [2010-11-17 Wed 12:22]
61   
62   ,  I need to look spiffy for the big day!
63   
64   ,   - [ ] Suit
65   ,   - [ ] Tie
66   ,   - [ ] Shoes
67   ,   - [ ] Hat
68   
69   ,  Possible stores to visit:
70   ,  
71   ,  | Store           | Location               | Miles away |
72   ,  |-----------------+------------------------+------------|
73   ,  | The Suit King   | 1000 E. Washington St. |        5.1 |
74   ,  | Mr. Haberdasher | 259 Western Rd.        |        7.2 |
75   
76 #+end_src
78 The sample entry above has the following metadata:
80  - todo keyword :: TODO
81  - scheduled timestamp :: 2010-12-01 Wed
82  - inactive timestamp :: 2010-11-17 Wed 12:22
83  - property :: estimated-cost \Rightarrow 100
84  - tags :: "wedding", "important", and "errands"
86 The entry also contains some text, including a checklist and a table.
88 Normally, an Org-mode file/outline contains several entries such as
89 the one above, nested hierarchically. Moreover, Org users typically
90 make their most important files available for easy searching by adding
91 them to their list of [[http://orgmode.org/manual/Agenda-files.html#Agenda-files][agenda files]], either selecting them one-by-one
92 with =C-c [= or by setting the variable =org-agenda-files=.
94 * The agenda as a search engine
95   :PROPERTIES:
96   :CUSTOM_ID: agenda-as-search-engine
97   :END:
99 For querying a collection of org files, Org-mode includes a powerful
100 built-in search-engine, [[http://orgmode.org/manual/Agenda-Views.html#Agenda-Views][the agenda]] (=C-c a=). As its name suggests,
101 the most common use of [[http://orgmode.org/manual/Agenda-Views.html#Agenda-Views][the agenda]] is to pull together, from all the
102 agenda files, a daily or weekly schedule or a list of todos. But the
103 agenda is also a powerful search engine that offers various ways tools
104 for querying both the metadata and the text of org-mode entries. In
105 fact, Org-mode's default agenda view (=C-c a a= or =org-agenda-list=)
106 is simply a search tool that gathers and displays all org-mode entries
107 with certain types of metadata---timestamps that fall within a given
108 range of dates.
110 Typing =C-c a= or =M-x org-agenda= brings up the agenda dispatcher, an
111 overview of Org-mode's various search tools:
113 : Press key for an agenda command:        <   Buffer, subtree/region restriction
114 : --------------------------------        >   Remove restriction
115 : a   Agenda for current week or day      e   Export agenda views
116 : t   List of all TODO entries            T   Entries with special TODO kwd
117 : m   Match a TAGS/PROP/TODO query        M   Like m, but only TODO entries
118 : L   Timeline for current buffer         #   List stuck projects (!=configure)
119 : s   Search for keywords                 C   Configure custom agenda commands
120 : /   Multi-occur                         ?   Find :FLAGGED: entries
122 A quick perusal of [[http://orgmode.org/manual/Built_002din-agenda-views.html#Built_002din-agenda-views][the commands]] here reveals that one can query for a
123 wide variety of data. This tutorial will focus on three searches in
124 particular:
126  - =C-c a T= :: for todo keywords
127  - =C-c a m=  :: for tags and properties
128  - =C-c a s= :: for full text searches
130 Now, let's look at the syntax for each of these search tools.
132 * Searching metadata (todos, tags, and properties)
133   :PROPERTIES:
134   :CUSTOM_ID: searching-metadata
135   :END:
136 ** Todo keyword searches
137    :PROPERTIES:
138    :CUSTOM_ID: todo-keyword-searches
139    :END:
141 The simplest type of metadata query in org-mode is [[http://orgmode.org/manual/Global-TODO-list.html#Global-TODO-list][=org-todo-list=]]
142 (invoked with =C-c a T=). This function prompts the user for a search
143 string and then retrieves a list of outline headings containing the
144 TODOs specified in the search string.[fn:lowercase-t]
146 Since each outline heading can contain only one TODO keyword, the
147 search syntax is quite simple, consisting either of a single keyword
148 or two or more keywords bound together by the boolean operator =|=
149 ("or").
151 For instance, the following query...
153 : TODO
155 ...retrieves all entries marked with a TODO keyword, whereas...
157 : TODO|PROJECT|MAYBE
159 ...displays a list of all headlines containing either TODO or PROJECT
160 or MAYBE.
162 [fn:lowercase-t] Note that the lowercase variant of the command (=C-c
163 a t=) does not provide a search prompt, but simply pulls up all active
164 TODOs.
166 ** Tag searches
167    :PROPERTIES:
168    :CUSTOM_ID: tag-searches
169    :END:
170 #+INDEX: tags
171 #+INDEX: search!tags
173 Though the org-todo-list serves its purpose well, it is limited to
174 only one type of metadata. If you would like to search for other types
175 of metadata, or mix and match a search for todo keywords with, say, a
176 search for tags, org-mode offers a more powerful tool,
177 [[http://orgmode.org/manual/Matching-tags-and-properties.html#Matching-tags-and-properties][=org-tags-view=]], which is called with the following keys:
179    - =C-c a m= :: searches all headlines
180    - =C-c a M= :: searches only headlines with active todos
182 At its simplest, org-tags-view does exactly what it says: it queries
183 for headlines marked with particular combinations of tags. The syntax
184 for such searches follows a simple boolean logic:
186  - =|= :: or
187  - =&= :: and
188  - =+= :: include matches
189  - =-= :: exclude matches
191 Here are a few examples:
193 1. =+computer&+urgent=
195    ...will result in all items tagged both computer *and* urgent,
196    while the search...
198 2. =+computer|+urgent=
200    ...will result in all items tagged *either* computer *or* urgent.
201    Meanwhile, the query...
203 3. =+computer&-urgent=
205    ...will display all items tagged computer *and not* urgent.
207 As you may have noticed, the syntax above can be a little verbose, so
208 org-mode offers convenient ways of shortening it. First, =-= and =+=
209 imply "and" if no boolean operator is stated, so example three above
210 could be rewritten simply as:
212 : +computer-urgent
214 Second, inclusion of matches is implied if no =+= or =-= is present,
215 so example three could be further shortened to:
217 : computer-urgent
219 Example number two, meanwhile, could be shortened to:
221 : computer|urgent
223 *** Grouping tags
224     :PROPERTIES:
225     :CUSTOM_ID: grouping-tags
226     :END:
228 There is no way (as yet) to express search grouping with parentheses.
229 The "and" operators (=&=, =+=, and =-=) always bind terms together
230 more strongly than "or" (=|=). For instance, the following search...
232 : computer|work+email
234 ...results in all headlines tagged either with "computer" or both
235 "work" and "email". An expression such as =(computer|work)&email= is
236 *not* supported at the moment.
238 There, are, however several other ways to achieve the grouping effect
239 of parentheses:
241 1. Use a regular expression
243    To invoke the "grouping" logic of parentheses, you can construct a
244    regular expression:
246    : +{computer\|work}+email
248    Note: you can also use the special property =ALLTAGS= (which
249    queries the same data as a normal tags search) together with a
250    regular expression:
252    : ALLTAGS={computer\|work}+email
253    
254    (In the next section we'll learn more about how property searches
255    and regular expressions are constructed.)
257 2. Use a slightly more verbose query as a substitute for the logic of
258    parentheses. E.g.,
260    : computer&email|work&email
262    This search will match all headlines tagged either with "computer"
263    and "email" or with "work" and "email."
265 3. If you are combining a tags search with a TODO search, you can use
266    the following:
268    : computer|email/!NOW
270 4. Use [[http://orgmode.org/manual/Agenda-commands.html#Agenda-commands][agenda filtering]].
272    Simply search for all headlines tagged with "computer" or "work"
273    and then use the agenda's tag filtering capabilities (=/=) to see
274    only those headlines among the results that have the tag "email."
276 ** Property searches
277    :PROPERTIES:
278    :CUSTOM_ID: property-searches
279    :END:
281 Org-mode allows outline entries to contain any number of [[http://orgmode.org/manual/Properties-and-Columns.html#Properties-and-Columns][arbitrary
282 data pairs]], which are conveniently hidden within a folding PROPERTIES
283 drawer, e.g.:
285 #+begin_src org
286   ,* TODO Evensong's magisterial work on the Amazon           :science:read:BIB:
287   ,  SCHEDULED: <2010-11-20 Sat>
288   ,  [2010-11-16 Tue 23:11]
289   ,  :PROPERTIES:
290   ,  :BIB_AUTHOR: Walter Evensong
291   ,  :BIB_TITLE: Mysteries of the Amazon
292   ,  :BIB_PAGES: 1234
293   ,  :BIB_PUBLISHER: Humbug University Press
294   ,  :END:
295   ,  
296   ,  Lots of good stuff on Brazil.
297 #+end_src
299 Let's imagine a free software aficionado named Mr. Gnu has added a
300 number of similar bibliographical outline nodes to his org files and
301 that he would like to find all entries that contain "Walter Evensong"
302 in their =BIB_AUTHOR= field. He can construct such a search so by
303 calling =org-tags-view= and entering the desired key/value match:
305 : C-c a m 
306 : Match: BIB_AUTHOR="Walter Evensong"
308 Property searches can be mixed and matched with tag searches. If Mr.
309 Gnu would like to see all books by "Walter Evensong" with the tag
310 "read", he can simply join the two desired matches together with the
311 =+= sign:
313 : BIB_AUTHOR="Walter Evensong"+read
315 Properties with numeric values can be queried with inequalities. If
316 Mr. Gnu would like to retrieve all books by the prolific Walter
317 Evensong that span over 1000 pages, he could enter the following:
319 : BIB_AUTHOR="Walter Evensong"+BIB_PAGES>1000
321 The comparison operators for searches are as follows:
323 : = (equal), > (greater than), <= (greater than or equal to), 
324 : < (less than), <= (less than or equal to), <> (not equal)
326 What if Mr. Gnus would to like of find all books by Walter Evensong
327 *or* any books over 1000 pages?
329 : BIB_AUTHOR="Walter Evensong"|BIB_PAGES>1000
331 For his own clarity, Mr. Gnu can always insert "+" signs, though they
332 are not required:
334 : +BIB_AUTHOR="Walter Evensong"|+BIB_PAGES>1000
336 It is important to note that the equal sign in the searches above
337 implies an exact match. If Mr. Gnu is searching for a string, such as
338 "Mysteries of the Amazon", the entire search query must match. Thus,
339 the search...
341 : BIB_TITLE="Amazon"
343 ...will not match the entry above. 
345 How then can you search for partial matches? The answer is regular
346 expressions. Instead of surrounding your query with quotation marks
347 (which will necessitate a precise and complete match), you can instead
348 enfold it in brackets, which instructs Org-mode to treat the query as
349 a regular expression. Thus, the search...
351 : BIB_TITLE={Amazon}
353 ...will locate all entries that match contain the sequence "Amazon"
354 and pull them up in the agenda:
356 : Headlines with TAGS match: BIB_TITLE={Amazon}
357 : Press `C-u r' to search again with new search string
358 :  org:        TODO Evensong's magisterial work on the Amazon  :science:read:BIB:
360 Mr. Gnu jots down the following rule in his growing org file collection:
362 #+begin_src org
363   ,* Tags/property search matching
364   , - For exact matches, use quotation marks.
365   , - For partial matches, use curly brackets.
366 #+end_src
368 [[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
369 for some strange reason Mr. Gnu would like to find all books
370 containing either "Amazon" or "Amazing" in their titles. The following
371 regular expression search should do the trick:
373 : BIB_TITLE={Amaz\(on\|ing\)}
375 Let's break this expression down:
377  - =Amaz= :: This is the string shared by both words.
378  - =\(...\)= :: These parentheses create a grouping to set off the
379               alternative matches that follow "Amaz".
380  - =on\|ing= :: =\|= is the "or" expression. Since it is placed within
381               the parentheses, it means that a match must begin with
382               "Amaz" but can end *either* in "on" *or* "ing".
384 You may be wondering why the search query contains so many
385 backslashes. It is because Emacs' regular expression engine gives the
386 characters =(=, =)=, and =|= a special meaning only when they are
387 "escaped" (i.e., preceded by a backslash). Thus, Mr. Gnu had simply
388 typed =BIB_TITLE={Amaz(on|ing)}=, he would have instructed Org-mode to
389 match entries with the exact sequence =Amaz(on|ing)= (an unlikely
390 match, unless he has a large collection of literary theory from the
391 1990s).
392               
393 Here's a simpler example. If Mr. Gnu would like to find all entries
394 with either "Walter" or "Evensong" in the author field, he could type:
396 : BIB_TITLE={Walter\|Evensong}
398 If he would like to pull up all entries that have defined value for
399 the =BIB_TITLE= property, he can simply use a single dot to match any
400 character:
402 : BIB_TITLE={.}
404 ** Special Properties
405    :PROPERTIES:
406    :CUSTOM_ID: special-properties
407    :END:
409 In addition to any explicitly declared key/value property pairs, each
410 Org-mode entry also has a number of [[http://orgmode.org/manual/Special-properties.html#Special-properties][special (i.e., implicit)
411 properties]] that can be queried with =org-tags-view= (=C-c a m=). These
412 include, among other things, the entry's TODO state, tags (local and
413 inherited), category, priority, and timestamps (DEADLINE, SCHEDULED,
414 active, and inactive). See the [[#outline-nodes-as-data-containers][sample entry]] above for an illustration
415 of where these properties are typically found in an outline node.
417 To see all of the properties (both explicit and implicit) defined for
418 an Org-mode entry, place the following text in an org-mode entry and
419 evaluate it by typing C-x C-e after the closing parenthesis:
421 : (org-entry-properties nil)
423 Here's an example of how such "special properties" can be put to good
424 use in a search:
426 : C-c a m
427 : Match: Effort>1+PRIORITY="A"+SCHEDULED<"<tomorrow>"+ALLTAGS={computer\|email}
429 This query finds all items with:
431 1. An estimated effort greater than one hour
432 2. A priority of "A"
433 3. A scheduled date "less than" tomorrow (i.e., today or earlier).
434 4. Either the tag "computer" or the tag "email"
435    - Note: the ALLTAGS property includes inherited tags, while the
436      TAGS property includes only local tags.
437    - This search is also a good example of how to achieve a [[#grouping-tags][grouping
438      logic without parentheses]] while querying tags.
440 Please [[http://orgmode.org/manual/Matching-tags-and-properties.html][consult the manual]] for a fuller explanation of the syntax of
441 such searches.
443 *** Querying timestamps
444     :PROPERTIES:
445     :CUSTOM_ID: querying-timestamps
446     :END:
448 A few words should be said here about querying timestamps contained in
449 the following properties: =DEADLINE=, =SCHEDULED=, =TIMESTAMP= (the
450 first active timestamp in an entry), and =TIMESTAMP_IA= (the first
451 inactive timestamp in an entry).
453 The basic syntax for querying timestamps is a time string enclosed in
454 double quotes and angular brackets. E.g., the search...
456 : C-c a m
457 : Match: +SCHEDULED="<2010-08-20 Sat>"
459 ...will find all items scheduled for Saturday, August 20, 2010
460 *without* a time of day specification. This last caveat is important
461 to note: if you have a timestamp with time of day information, such
462 as...
464 #+begin_src org
465   ,* Some task
466   ,  SCHEDULED: <2010-08-20-Sat 10:30>
467 #+end_src
469 ...the search above will not retrieve it. (This is not normally a
470 problem, since the daily/weekly agenda view provides a far superior
471 mechanism for viewing all timestamps that fall on a particular day.)
473 The true value of timestamp property queries lies in the use of
474 inequalities to capture a range of dates. To assist with this task,
475 Org-mode provides a number of convenient shortcuts:
477  - =<today>= and =<tomorrow>= :: timestamps for today and tomorrow
478       (without a time of day specification)
479  - =<now>= :: right now, including time of day
480    - e.g., =2010-11-20 Sat 12:42=
481  - =<-5d>=, =<-10w>=, =<+3m>=, =<+1y>= :: relative date indicators
482     - the shortcuts above indicate five days ago, ten weeks ago, three
483       months from now, and one year from now
485 To see all items SCHEDULED far in the future, say, more than a year
486 from now, you could type:
488 : C-c a m
489 : Match: SCHEDULED>"<+1y>"
491 Here's another scenario. Imagine you use org-capture to take all your
492 notes and that you automatically stamp each notes with an inactive
493 timestamp. To find all notes you took in the past two weeks with the
494 tag "chimpanzees", you could perform the following search:
496 : C-c a m
497 : Match: chimpanzees+TIMESTAMP_IA>="<-2w>"
499 *** Limit tags and properties searches by TODO state
500     :PROPERTIES:
501     :CUSTOM_ID: limiting-searches-to-todos
502     :END:
504 You can limit any of these tags/property searches to active todo
505 states simply by using =C-c a M= instead of =C-c a m=.
507 You can also, of course, limit the searches to a particular todo
508 keyword (say, NEXT) by adding...
510 : +TODO="NEXT"
512 ...to any of the searches above. But Org-mode also provides a
513 convenient (and more efficient) syntax for limiting searches to
514 particular TODO keywords. Simply add a =/= followed by a TODO search
515 in the form [[#todo-keyword-searches][we've already discussed]]. For instance, to limit the
516 chimpanzee search above to items marked DONE, you could type:
518 : C-c a m
519 : Match: chimpanzees+TIMESTAMP_IA>="<-2w>"/DONE
521 As with normal todo searches, you can use or (=|=) to expand the
522 allowed matches. For instance, the query...
524 : chimpanzees+TIMESTAMP_IA>="<-2w>"/TODO|NEXT
526 ...will match against items marked either TODO or NEXT.
528 If you are matching only against active todos (i.e., things not marked
529 done), you can make your search more efficient by adding an exclamation
530 point. E.g., the following search...
532 : computer/!TODO|NEXT
534 ...will result in all items tagged "computer" and either a TODO or
535 NEXT keyword. The exclamation mark will speed up the search, because
536 org-mode will only query items that have an active todo keyword (as
537 defined either in the variable =org-todo-keywords= or in =#+TODO=
538 declarations at the top of an org file). For instance, if you had
539 placed the following line at the top of your org files...
541 : #+TODO: TODO NEXT STARTED WAITING | DONE CANCELED
543 ...an exclamation point limit the possible matches items marked TODO,
544 NEXT, STARTED, or WAITING.
546 You can use a a negative (=-=) to exclude TODO states. The search...
548 : computer/!-WAITING
550 ...will result only in items marked TODO, NEXT, or STARTED.
552 Be careful to avoid using "and" logic when you query TODOs, since each
553 item, by definition can have only one TODO state. Take a look at the
554 following two searches:
556 : computer/!WAITING+TODO
558 : chimpanzees+TODO="TODO"+SCHEDULED<="<+1w>"+TODO="WAITING"
560 These searches will *never* return any positive results, since an org
561 entry cannot have both a TODO *and* a WAITING keyword.
563 * Searching the full text of entries
564   :PROPERTIES:
565   :CUSTOM_ID: searching-entry-text
566   :END:
567 ** Keyword searches
568    :PROPERTIES:
569    :CUSTOM_ID: keyword-searches
570    :END:
572 Thus far, we have explored different ways to query the various types
573 of metadata attached to an org entry. But what if you would like to
574 search the entire text of your org entries?
576 The answer: call [[http://orgmode.org/manual/Search-view.html#Search-view][=org-search-view=]] with =C-c a s=. In the agenda
577 dispatcher, this appears as...
579 : s  Search for keywords
581 Don't be fooled by the word "keywords," which some programs use as a
582 synonym for tags. Here, a keyword search scours the full text of org
583 entries.
585 Let's start with an example:
587 Desperately in need of typing practice (as if Emacs does not provide
588 enough keyboarding practice), our friend Mr. Gnu would like to locate
589 the following entry, which is buried somewhere in his agenda files:
591 #+begin_src org
592   ,* A sentence to test my keyboarding skills
593   
594   ,The quick brown fox jumped over the lazy dog.
595 #+end_src
597 Mr. Gnu vaguely remembers that the entry contains the word "fox", so
598 he pecks at the keyboard to enter...
600 : C-c a s 
602 He is confronted with the prompt...
604 : [+-]Word/{Regexp} ...: 
606 ...so he enters...
608 : fox
610 ...and receives an agenda buffer with the correct results:
612 : Search words: fox
613 : Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit
614 :  typing:        A sentence to test my keyboarding skills
616 Here, we should note that Org-mode's keyword searches are
617 *case-insensitive*, so "fox" will match any of the following: "fox",
618 "Fox", "FOX", etc.
620 Let's say, however, that Mr. Gnu's day job involves studying the
621 behavior of foxes, so he knows ahead of time that a simple search will
622 bring up hundreds of results. In addition, he recalls that the desired
623 entry also contains the word "dog". Thus, he enters the following:
625 : C-c a s
626 : [+-]Word/{Regexp} ...: fox dog
628 Somewhat puzzlingly, Mr. Gnu's search yields no results. What went
629 wrong?
631 Mr. Gnu consults [[http://orgmode.org/manual/Search-view.html#Search-view][the manual]] and finds that the default behavior of
632 =org-search-view= is to treat the entered query as a single string, so
633 when he typed =fox dog=, Org-mode looked quite literally for
634 =fox[whitespace]dog=.
636 Mr. Gnu further finds that to treat "dog" and "fox" as boolean
637 keywords that can be located anywhere in the entry, he needs to
638 precede each term with a =+=. (Technically, he only needs to precede
639 the first search term with =+= to initiate a boolean search, but he
640 decides to put =+= in front of both for the sake of clarity.) So he
641 types...
643 : C-c a s
644 : [+-]Word/{Regexp} ...: +fox +dog
646 ...and is overjoyed to retrieve the expected results.
648 Mr. Gnu makes a mental note: unless the first character of the search
649 query is a =+=, Org-mode will treat the entire query as a single
650 string. Thus, the query...
652 : fox +dog
654 ...will prompt Org-mode to search for the single string "fox +dog".
655 (To change this behavior, please read the
656 [[#boolean-searches-by-default][section for "Google addicts" below]].)
658 Later, while at work, Mr. Gnu  wants to find all entries on foxes that
659 do not contain the word dog, so he types...
661 : C-c a s
662 : [+-]Word/{Regexp} ...: +fox -dog
664 If Mr. Gnu wants to incorporate a substring/phrase into a boolean
665 search (i.e., a query with a =+= at the beginning), he can use
666 quotation marks:
668 : +fox +"lazy dog"
670 At home again, while practicing typing, Mr. Gnu wants to find all
671 entries that contain either the word "keyboarding" or the word
672 "typing". Remember his lessons on tag searches, he tries the following
673 search query:
675 : +keyboarding|+typing
677 Alas, the search returns no results, because Mr. Gnu just instructed
678 Org-mode to look for the entire string "keyboarding|+typing." Reading
679 the manual, Mr. Gnu discovers that, unlike todo and tag searches,
680 keyword searches require separate terms to be separated by whitespace
681 (e.g., =+fox +dog=). In addition, Mr. Gnus realizes that keyword
682 searches have only two simple boolean expressions: =+= ("and") and =-=
683 ("and not"). There is no "or" symbol, such as =|=. What then should
684 Mr. Gnu do to find entries containing keyboarding *or* typing?
686 ** Full text search using regular expressions 
687    :PROPERTIES:
688    :CUSTOM_ID: regexps-in-org-search-view
689    :END:
691 The solution to Mr. Gnu's puzzle is found in regular expressions.
692 Indeed, Mr. Gnu deduced as much by glancing at the org-search-view
693 prompt:
695 : [+-]Word/{Regexp} ...:
697 As the prompt suggests, Mr. Gnu can search org-entries using Emacs'
698 powerful regular expression engine. To do so, he simply needs to
699 enclose the regular expression in brackets. So he types...
701 : C-c a s
702 : [+-]Word/{Regexp} ...: +{keyboarding\|typing}
704 ...to find all entries that contain either "keyboarding" or "typing".
705 (Mr. Gnu could also have used parentheses to create a more compact
706 search query, such as =+{\(keyboard\|typ\)ing}=. Also, it is good to
707 recall here that =(=, =|=, and =)= only become special characters only
708 when escaped with a =\=.)
710 Regular expressions, Mr. Gnu finds, can be combined with words. The
711 query...
713 : +{keyboarding\|typing} +fox
716 ...finds the "quick brown fox" entry above, while...
719 : +{keyboarding\|typing} -fox
721 ...excludes it, finding only those entries that contain either the
722 word "keyboarding" or "typing" and *not* the word dog.
724 Again, Org-mode's default behavior is to treat the entire query as a
725 single string unless it sees a =+= or a ={= at the beginning of the
726 line. So if Mr. Gnus types...
728 : dog +{keyboarding\|typing} 
730 ...Org-mode will search for the entire substring "dog
731 +{keyboarding\|typing}". (If you don't like this behavior, please read
732 [[#boolean-searches-by-default][the section for "Google addicts" below]].)
734 *** Regular expression syntax
735     :PROPERTIES:
736     :CUSTOM_ID: regular-expression-syntax
737     :END:
739 The possibilities afforded by regular expressions are myriad. The
740 examples discussed here are relatively basic. For a thorough
741 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
742 lisp manual]].
744 Let's look at a couple of examples:
746 Imagine you've entered a lot of contact entries with phone numbers in
747 the conventional U.S. format: 123-456-6789. To find all Org-mode
748 entries with such numbers, you could type:
750 : C-c a s
751 : [+-]Word/{Regexp} ...: +{[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}}
753 The square brackets here are special characters; they match any of
754 characters they enclose. For instance, =[abc]= matches either a or b
755 or c. In this particular case, the =[0-9]= matches any digit between 0
756 and 9. In addition, the escaped curly brackets (=\{...\}=) that
757 immediate follow the square brackets indicate how many times in a row
758 the character should occur. In this case, Org-mode will search for
759 the following sequence:
761   - exactly three digits
762   - a hyphen
763   - exactly three digits
764   - a hyphen
765   - exactly four digits
767 Instead of specifying the precise number of times a match such as
768 =[0-9]= must repeat, you can also use the following special
769 characters:
771  - =*= :: match any number of times (including none)
772  - =+= :: match at least once and possibly more
773  - =?= :: match either once or not at all
775 Now, imagine our friend Mr. Gnu is a new fan of Org-mode and has
776 jotted down a lot of notes on his favorite PIM. However, he have
777 entered the name Org-mode inconsistently, sometimes as "orgmode",
778 other times as "Org mode", and still other times as "Org-mode". He'd
779 like to find all his references to Org-mode, taking into account the
780 various spellings. Here's a simple query that will accomplish this:
782 : +{org[-\s]?mode}
784 Mr. Gnu just instructed Org-mode to search for any entry that contains
785 the character sequence "org", followed by a hyphen, a space, or no
786 character, followed by "mode". Since the search is case-insensitive,
787 it will match "org-mode", "org mode", or "orgmode".
789 ** Limiting full text searches
790    :PROPERTIES:
791    :CUSTOM_ID: limiting-full-text-searches
792    :END:
794 There are several convenient ways to refine and limit full text
795 searches.
797 First, if you find that a search produces too many results, you can
798 easily add a new word or regexp by typing any of the following in the
799 agenda buffer:
801  - =[= :: add a word (i.e., =+=)
802  - =]= :: exclude a word (i.e., =-=)
803  - ={= :: add a regexp (i.e., =+{}=)
804  - =}= :: exclude a regexp (i.e., =-{}=)
806 Let's say Mr. Gnu searches for the words Carsten *and* Dominik:
808 : C-c a s
809 : [+-]Word/{Regexp} ...: +Carsten +Dominik
811 Since Mr. Gnu is an avid reader of the Org-mode mailing list and a
812 heavy user of org-capture, he discovers that he has hundreds of
813 entries that include Carsten's name. He wants to limit the search only
814 to entries with an inactive timestamp from November of 2010. So he
815 types =[= in the agenda buffer to add a new search term and receives the
816 following prompt...
818 : [+-]Word/{Regexp} ...: +Carsten +Dominik +
820 ...with the cursor conveniently located after the plus sign. He
821 completes the query to find inactive timestamps from November...
824 : [+-]Word/{Regexp} ...: +Carsten +Dominik +[2010-11-
826 ...and voilà, he retrieves a smaller subset of results.
828 If Mr. Gnu wants to find both active and inactive timestamps, he could
829 instead type ={= to add a regular expression:
831 : [+-]Word/{Regexp} ...: +Carsten +Dominik +{[\[<]2010-11-}
833 Similarly, if Mr. Gnu wants to guarantee the precision of his match,
834 he could use a detailed regular expression...
836 : +{\[2010-11-[0-9]\{2\}\s-[A-Za-z]\{3\}\(\s-[0-9]\{2\}:[0-9]\{2\}\)?\]}
838 But Mr. Gnu quickly decides that searching for the string "[2010-11-"
839 good enough for his purposes.
841 Org-mode also provides convenient syntax for limiting full text
842 searches.
844 1. If you place an asterisk at the beginning of your search, Org-mode
845    will search only headlines (and not entry text). E.g., to find all
846    entries with "emacs" in the headline, you could type:
848    : C-c a s
849    : [+-]Word/{Regexp} ...: *+emacs
851 2. If you place an exclamation mark at the beginning of the query,
852    Org-mode will only pull up entries that are active todos:
854    : !+emacs
856    (You can also limit your search to active todos by using a prefix
857    argument: =C-u C-c a s=.)
859 3. Finally, if you place a colon at the beginning of a query, the
860    boolean words you provide will only match entire words. Thus the
861    following search...
863    : :+emacs
865    ...will match "emacs" but not "emacswiki".
867 You can mix and match these three limiting symbols, but they will only
868 work if they appear in the correct order: i.e., =*= -> =!= -> =:=. If
869 you type =:!+emacs=, your search will not retrieve any results.
871 ** Combining metadata and full text queries
872    :PROPERTIES:
873    :CUSTOM_ID: combining-metadata-and-full-text-queries
874    :END:
876 As an expert on tag and property searches, you might ask: is it
877 possible to combine metadata and full text searches? For instance, how
878 could Mr. Gnu find all entries with "Walter Evensong" in the
879 =BIB_AUTHOR= field, the todo keyword "DONE", and the word "Brazil" in
880 the full text of the entry?
882 - It is not possible to simply combine the syntax of metadata and
883   full text searches. Org-mode parses each query in fundamentally
884   different ways.
886 - You can, however, easily accomplish "mixed" queries by using regular
887   expressions and =org-search-view=. In some instances,
888   =org-search-view= offers an easier and more efficient way of
889   querying metadata than the tags and property search.
891 The simplest way to think about Org-mode metadata is as different
892 types of markup patterns. Tags are enclosed in colons, todo keywords
893 directly follow the asterisks that mark outline headings, timestamps
894 are contained in brackets and have the pattern =YYYY-MM-DD DOW HH:MM=,
895 and so on. Thus, to query for particular types of metadata, one simply
896 has to construct regular expressions that match these patterns.
898 Back to Mr. Gnu, our mediocre typist and reader of very long books.
899 Today, he would like to find all entries in which:
901  - the =BIB_AUTHOR= is "Walter Evensong"
902  - the todo keyword is "DONE"
903  - the word "Brazil" appears in the full text. 
905 First, he invokes =org-search-view=:
907 : C-c a s
909 At the prompt, he adds a plus sign and the word "brazil":
911 : [+-]Word/{Regexp} ...: +brazil
913 He remembers that he must add the plus sign to instruct Org-mode to
914 treat this search as a boolean search. Otherwise it will simply look
915 for the entire string entered at the prompt.
917 Next he needs to search for the todo keyword "DONE". Since todo
918 keywords immediately follow the markup for outline headings, he can
919 simply add a regexp that matches an outline heading immediately
920 followed by the word DONE:
922 : [+-]Word/{Regexp} ...: +brazil +{^\*+\s-+DONE\s-}
924 This regexp begins with =^=, which forces a match at the beginning of
925 the line. It is followed by an asterisk, which needs to be escaped,
926 since an asterisk a special character in regular expressions. the =+=
927 after the asterisk instructs Org-mode to look for one or more
928 asterisks, while the =\s-+= indicates that at least one space follows
929 the asterisk(s). So Mr. Gnu is searching for at least one asterisk at
930 the beginning of the line followed by a space---the very definition of
931 an outline heading in Org-mode. And the keyword DONE followed by
932 whitespace completes the match. If Mr. Gnu would like to match more
933 than one todo keyword, say DONE or WAITING, he could use grouping:
934 =+{^\*+\s-+\(DONE\|WAITING\)\s-}=
936 Finally, Mr. Gnu finishes his query by searching for the property
937 =BIB_AUTHOR=. He recalls that a property line looks like this:
939 : :BIB_AUTHOR: Walter Evensong
941 With this in mind, he can easily construct a regexp to search for the
942 string =:BIB_AUTHOR:= followed by an arbitrary amount of whitespace
943 followed in turn by the string "Walter Evensong".
945 : [+-]Word/{Regexp} ...: +brazil +{^\*+\s-+DONE\s-} +{:BIB_AUTHOR:\s-+Walter Evensong}
947 Mr. Gnu is surprised at the speed with which Org-mode returns his
948 results. Indeed, he finds that regexp searches (especially those
949 querying properties) usually return their results more quickly than
950 property and tag searches. And he deduces the reason: whereas property
951 searches have to query each headline to determine whether a given
952 property contains a value, keyword searches simply scan each file for
953 matches and then return the appropriate headlines.
955 In many instances, of course, the DONE regexp above may be overkill.
956 Searching for the string "* DONE" will often do the trick. E.g.,
958 : [+-]Word/{Regexp} ...: +brazil +"* DONE"
960 Indeed, Mr. Gnu could probably also dispense with the =:BIB_AUTHOR:=
961 regexp above, simply typing...
963 : [+-]Word/{Regexp} ...: +brazil +"* DONE" +":BIB_AUTHOR: Walter Evensong"
965 Here's another example. Let's say Mr. Gnu would like to find all
966 active todos directly tagged "urgent" (i.e., not inherited) with the
967 word "wedding" somewhere in the entry text. The following keyword
968 search does the trick:
970 : C-c a s
971 : [+-]Word/{Regexp} ...: !+wedding :urgent:
973 If Mr. Gnu wants to see either the tag "urgent" or the tag
974 "important", he could use a regular expression:
976 : !+wedding +{:\(urgent\|important\):}
978 The main limitation of such searches is that keyword searches know
979 nothing of outline tree inheritance. Thus, if Mr. Gnu is interested in
980 all entries that inherit the tag "urgent", he should always use
981 =org-tags-view=.
983 ** Searching additional files
984    :PROPERTIES:
985    :CUSTOM_ID: searching-additional-files
986    :END:
988 Often, the set of files one would like to search by keyword is larger
989 than one's set of active agenda files. For instance, one might archive
990 old projects in separate files so that they no longer contribute to
991 the agenda. Yet one would still like to search the reference material
992 in these projects by keyword/regexp.
994 The solution lies in the variable
995 =org-agenda-text-search-extra-files=. Adding a list of files to this
996 variable instructs =org-search-view= to query those files in addition
997 to the agenda files. Note that setting
998 =org-agenda-text-search-extra-files= has no effect on other types of
999 agenda commands, such as todo and tags/property searches.
1001 ** Keyword searches for Google addicts
1002    :PROPERTIES:
1003    :CUSTOM_ID: boolean-searches-by-default
1004    :END:
1006 As noted before, =org-search-view= will treat a search query as a
1007 boolean expression only if it begins with either a =+= or a ={= (i.e.,
1008 a regular expression). Without these characters, Org-mode will treat
1009 the query as a single substring.
1011 This default syntax of =org-search-view= is thus different than the
1012 behavior of search engines such as Google, which treat searches as
1013 lazy boolean queries by default. If you type "emacs org-mode" into
1014 Google, it will not search for the literal string "emacs org-mode",
1015 but rather assume the space implies a boolean expression: "emacs and
1016 org-mode".
1018 If you find yourself often forgetting to add an initial =+= to your
1019 =org-search-view= queries, you can make "lazy booleans" the default
1020 behavior by adding the following to your .emacs:
1022 #+begin_src elisp
1023 (setq org-agenda-search-view-always-boolean t)
1024 #+end_src
1026 Then you can happily type your lazy searches:
1028 : C-c a s
1029 : [+-]Word/{Regexp} ...: org mode Carsten :email:
1031 If you would like to include a substring or phrase in your search, you
1032 can do so by enclosing it in quotation marks. And if you want to
1033 exclude items or use regular expressions, you will, of course, still
1034 have to use a minus sign and curly brackets, respectively.
1036 * Searching org files line-by-line
1037   :PROPERTIES:
1038   :CUSTOM_ID: line-by-line-search
1039   :END:
1041 All the searches we have discussed thus far return their results as a
1042 list of org headlines in the agenda buffer. Sometimes, however, you
1043 might prefer to see each line in which a word or regular expression
1044 occurs. There are different ways to do this:
1046 ** Multi-occur
1047    :PROPERTIES:
1048    :CUSTOM_ID: multi-occur
1049    :END:
1051 Org-mode uses Emacs' multi-occur command to search for any lines in
1052 the agenda files containing a regular expression. Simply type =C-c a
1053 /= followed by a word or regular expression and you will be presented
1054 a buffer with all lines that match the query, with each line
1055 conveniently linked to its original location.
1057 ** External commands and scripts
1058    :PROPERTIES:
1059    :CUSTOM_ID: grep-etc
1060    :END:
1062 Emacs provides convenient interfaces to common Unix search commands,
1063 such as grep. Simply type =M-x grep= and complete the query (the
1064 working directory is usually that of the current buffer in Emacs).
1065 Using grep is especially convenient when you want quickly to search
1066 org files that are not in =org-agenda-files= or
1067 =org-agenda-text-search-extra-files=. And, of course, grep can be used
1068 outside of Emacs.
1070 Since org-mode files are plain text, you can use your favorite
1071 scripting language (perl, awk, python, etc.) to develop new and ever
1072 more creative ways to search and analyze them.
1074 * Sparse trees
1075   :PROPERTIES:
1076   :CUSTOM_ID: sparse-tree-view
1077   :END:
1079 The commands we have examined so far typically search multiple files
1080 and display the resulting heading in a separate agenda buffer. But
1081 sometimes, you might want to search for various types of data within a
1082 single file, so as to see all the matching headlines and entries in
1083 context.
1085 The way to accomplish this is via a [[http://orgmode.org/manual/Sparse-trees.html#Sparse-trees][sparse tree view]] (=C-c /=), which
1086 collapses the outline in the current file, showing only the portions
1087 that match a query.
1089 Calling =org-sparse-tree= with =C-c /= brings up a prompt with several
1090 search options:
1092 : Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
1093 :              [d]eadlines [b]efore-date [a]fter-date
1095 Some of these search, such as "todo" (=t=) and "deadlines" (=d=) are
1096 quite simple, showing all headlines in a buffer that contain an active
1097 todo keyword or a deadline, respectively. Others, such as "property"
1098 (=p=), prompt for a single key/value pair.
1100 One search that may be of particular interest is "match" (=m=). This
1101 query uses exactly the same syntax as =org-tags-view=, allowing us to
1102 use complex metadata searches to create sparse trees
1104 For instance, to highlight all active todos *without* a timestamp in
1105 the current buffer, you could type:
1107 : C-c / m 
1108 : Match: -SCHEDULED={.}/!
1110 This instructs Org-mode to look for any active todo (=/!=) without a
1111 SCHEDULED timestamp.
1113 * Custom agenda commands
1114   :PROPERTIES:
1115   :CUSTOM_ID: custom-agenda-commands
1116   :END:
1118 If there are searches you perform again and again, you can easily save
1119 them by adding them to you [[http://orgmode.org/manual/Custom-agenda-views.html#Custom-agenda-views][custom agenda commands]].
1121 As we know, Mr. Gnu is an avid collector of very large books (which,
1122 of course, he manages in very long org files). Moreover, he often
1123 likes to peruse your inventory of books over 1,000 pages, querying his
1124 custom =BIB_PAGES= field. To save time and energy, Mr. Gnu could add a
1125 custom command such as the following to his =.emacs=:
1127 #+begin_src emacs-lisp
1128   (add-to-list 'org-agenda-custom-commands
1129                '("b" "Big books" tags "+BIB_PAGES>1000"))
1130 #+end_src
1132 Note that "tags" here indicates =org-tags-view=. Thus, the query uses
1133 the tags/property search syntax.
1135 Mr. Gnu realizes he can save an even faster version of the search
1136 above:
1138 #+begin_src emacs-lisp
1139   (add-to-list 'org-agenda-custom-commands
1140                '("B" "Big books (fast)" search "{:BIB_PAGES:\\s-+[0-9]\\{4\\}}"))
1141 #+end_src
1143 The symbol "search", as you might have guessed, instructs Org-mode to
1144 use =org-search-view=. And the saved search finds all items with
1145 =BIB_PAGES= property that contain four digits (i.e., > 1000 pages).
1147 You might notice that the search query here, compared with the one
1148 above, contains extra backslashes. That is because the backslash is a
1149 special character in emacs-lisp and thus needs to be escaped when
1150 placed in an =.emacs= file.
1152 If Mr. Gnu frequently need to perform the "urgent wedding tasks"
1153 search above, he could add a command such as the following:
1155 #+begin_src emacs-lisp
1156   (add-to-list 'org-agenda-custom-commands
1157                '("w" "Getting married next week!" 
1158                  search "!+wedding +{:\\(urgent\\|important\\):}"))
1159 #+end_src
1161 Finally, one can use custom commands to run searches with different
1162 local settings. For instance, one can set up a custom agenda command
1163 to run a tags/property search on files other than the agenda files:
1165 #+begin_src emacs-lisp
1166   (add-to-list 'org-agenda-custom-commands
1167                '("r" "Reference material" tags ""
1168                  ((org-agenda-files (file-expand-wildcards "~/ref/*.org")))))
1169 #+end_src
1171 For a full introduction to custom agenda commands, please see [[file:org-custom-agenda-commands.org][this
1172 tutorial]].